Day 2: Random Exercises

  1. This was more of a find around the library part.
# Write a Python program to get the Python version you are using.
# Write a Python program to display the current date and time.

import datetime
import sys

print(sys.version)
print(datetime.datetime.now())

 

2. Fiddling around with another library

# Write a Python program which accepts the radius of a circle from the user and compute the area.

import math

radius = int(input("Enter the radius of the circle: "))
area1 = math.pi * pow(radius, 2)
print(area1)
area2 = math.pi * radius**2
print(area2)

So in this as we see, there are two ways in which we can print the area:

  • Using math library, we can use the power function and pass on the value of our radius and the power to which it has to be raised.
  • Other is explicitly calling the exponential function using double asterisk.

 

3. This was more of a slicing function

# Write a Python program which accepts the user's first and last name
# and print them in reverse order with a space between them.

name = input("Enter your name please: ")
if len(name) > 0:
    print(name[::-1])

Slicing is a way in which we can split our set of string/number/lists and display certain set of characters from it.

 

Day 1: Sample String Output

# Write a Python program to print the following string in a specific format (see the output).
# Sample String : "Twinkle, twinkle, little star,
# How I wonder what you are! Up above the world so high,
# Like a diamond in the sky.
# Twinkle, twinkle, little star, How I wonder what you are"
#
# Output :
# Twinkle, twinkle, little star,
#  How I wonder what you are!
#     Up above the world so high,
#     Like a diamond in the sky.
# Twinkle, twinkle, little star,
#  How I wonder what you are

sampletext = """Twinkle, twinkle, little star,
How I wonder what you are! Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star, How I wonder what you are"""

newsample = """Twinkle, twinkle, little star,
\n \t How I wonder what you are! 
\n \t \t Up above the world so high,
\n \t \t Like a diamond in the sky.
\n Twinkle, twinkle, little star,
\n \t How I wonder what you are"""

print(newsample)

So lets start with the basics:

  1. # (aka hashtag) is used to comment a line.
  2. Single line strings are stored in either single quotes (‘…’) or double quotes (“…”).
  3. Multiple line strings are stored in triple quotes (“””…”””) or 3 single quotes.
  4. \n – Escape sequence used to add a new line.
  5. \t – Escape sequence used to add tab (space) before the text. Tab generally ends up adding 4 spaces before start of the string.

So the trick was very simple here. Using escape sequence, you can simply display your text in the manner asked.

Note:

  1. Using hash tag for multiple lines is not possible like what we did for multi line string. Hash tag needs to be added on each line.
  2. I’m using Pycharm by JetBrains. It is very similar to Visual Studio or any other heavy text editors. I googled a lot and ended up for this since I had previous experience with VS and I found it easy to have my words print before me even before I complete them. #lazyassproblems
  3. I think its a beautiful app though. 🙂

10 Days Later..: Cows & Bulls

# Create a program that will play the “cows and bulls” game with the user.
# Randomly generate 4 digit number.

import random

complist = '123456789'
compnum = random.sample(complist, 4)
compnum = list(map(int, compnum))  # To convert string array to int array since above makes a string list
# print(compnum)  # This shows your final output


def userinput():

    userinp = input("Please enter a 4 digit number: ")
    if len(userinp) < 4 or len(userinp) > 4:
        print("The value should be <> 4")
        userinput()
    else:
        userinp = [int(i) for i in str(userinp)]  # This converts the number to a list format
        print(userinp)
        checkdigits(userinp, compnum)


def checkdigits(userinp, compnum):

    bull_count = 0
    cow_count = 0

    for i in range(0, len(compnum)):
        if compnum[i] == userinp[i]:
            bull_count += 1

        for j in range(0, len(userinp)):
            if compnum[i] == userinp[j] and i != j:
                cow_count += 1
                
    if bull_count == 4:
        print("Congrats! Correct guess!")
        exit()
    elif cow_count >= 0 or bull_count >= 0:
        print("You have " + str(cow_count) + " cows and " + str(bull_count) + " bulls! Try again..? Y/N")
        tryagain = input()
        if tryagain.lower() == 'y':
            userinput()
        else:
            quit()

userinput()

 

I had a really really hard time figuring this one out. Honestly. There was a point where I just wanted to give up and mostly because I’m not well versed with lists. I was not aware that you could simple “array-fy” it and compare index values present in the list.

Day 16: Show all the headlines from NY Times using BeautifulSoup & Requests packages

So, I didn’t use requests package. I did download it, tried some things with it, but it didn’t help and I didn’t get it.

Although I did find an alternative to it – urllib (since I’m on Python 3.6).

# Use the BeautifulSoup and requests Python packages
# to print out a list of all the article titles
# on the New York Times homepage.

import string
from bs4 import BeautifulSoup
from urllib.request import urlopen

testurl = 'https://www.nytimes.com/'
soup = BeautifulSoup(urlopen(testurl), 'lxml')
print(soup.prettify())
newheadings = soup.find_all(class_="story-heading").__str__()
test = str.strip(newheadings, '</a>')
print(test)

I’ll try it out using requests library.

Lessons Learned:

  1. New libraries – BeautifulSoup, Requests, urllib
  2. BeautifulSoup and Requests are external libraries which needs be installed using pip/easy_install.
  3. Conversion of ResultSet to String which is done by this LOC:

     soup.find_all(class_=”story-heading”).__str__()

  4. Using strip – which is used to strip of characters or blank spaces before or after (check this link) – does not work for me. Need to seriously figure this out.
  5. Copy-pasting your own running code, ends up not working. Re-write the whole thing which clear head as to what you want. Since I’m still learning and still get to know a lot of things, but by knowing what you want your code to do will make it easy. [Enough philosophy!]
  6. NY Times has a very shabby page though. No offence to the designers as well.
  7. This was tough. Seriously.
  8. Prettify – Shows your page in an XML format which is pretty cool.
  9. Oh and here’s the link to see the difference. Sorry. I really need to study more.

Day 15: Generate Random Password

# Write a password generator in Python.
# strong passwords have a mix of lowercase letters, 
# uppercase letters, numbers, and symbols.
# The passwords should be random, generating a new password 
# every time the user asks for a new password.
# Include your run-time code in a main method.


import string
import random

characters = string.ascii_letters
chartest = [characters[i] for i in range(len(characters))]
digits = string.digits
special = string.punctuation
randomValue = characters + digits + special


def createpassword(randomValue, passlen):
    password = ''.join(random.sample(randomValue, passlen))
    return password


def mainstart():
    passlen = int(input("Enter the length of your password greater than 6: "))
    if passlen < 6:
        print("Password should be greater than 6. Retry!")
        mainstart()
    else:
        password = createpassword(randomValue, passlen)
        print(password)
        reqagain = input("Want to try again? Y/N ").lower()
        if reqagain == 'y':
            mainstart()
        else:
            quit()


mainstart()

Day 14: Listing with String Part 2

# Write a program that asks the user for 
# a long string containing multiple words.
# Print back to the user the same string, 
# with the words in backwards order.

def inputstring():
    testing = input("Enter a string: ")
    a = len(testing)
    printwordsback(a, testing)


def printwordsback(a, testing):
    if a > 1:
        set2 = [testing[i] for i in range(len(testing))]
        print(set2)
        for i in range(len(set2)):
            set1 = set2[::-1]
            print(' '.join(set1))
            break

inputstring()

Lessons Learned:

  1. How to split the string into individual characters.

Day 14: Listing with Strings Part 1

# Write a program that asks the user for a long string containing 
# multiple words.
# Print back to the user the same string, 
# except with the words in backwards order.

def inputstring():
    testing = input("Enter a string: ")
    a = len(testing)
    printwordsback(a, testing)


def printwordsback(a, testing):
    if a > 1:
        listing = testing.split()
        for i in range(a + 1):
            set1 = listing[::-1]
            print(' '.join(set1))
            break


inputstring()

Lessons Learned:

  1. Converting a list to string can be done by join. Giving space between the single quotes adds space between the texts.
  2. If you want to print all the characters in reverse order, [: : -1 ] is to be used.

Day 13: Listing again!

 

# Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
# and makes a new list of only the first and last elements of the given list.
# For practice, write this code inside a function.

import random


def mainstart():
    testing = int(input("Enter the length of the array: "))
    input_array(testing)


def input_array(testing):
    a = [random.randint(0, 100) for i in range(testing)]
    print("Array: "  + str(a))
    # take_array(a)
    printfirstandlast(testing, a)


def printfirstandlast(testing, a):
    c = []
    for i in range(testing):
        b = a[0]
        c.append(b)
        b = a[-1]
        c.append(b)
        break

    print(c)


mainstart()

Lessons Learned:

  1. I need to start practicing regularly. I’m forgetting what I’m learning.
  2. If you slice a list and append it, then list of list will be formed and not a simple one. [[num1], [num2]] – Wrong
    Instead [num1, num2] – Correct
  3. I was getting continuous error on runtime when I tried running the code only to realise that my last function printfirstandlast I was passing the incorrect variable. So in short when I had to pass two variables, I was only passing one (only the array) and even in my range function I had passed the incorrect variable (the array instead of the length).

Day 12: Prime Number

 

# Ask the user for a number and determine whether the number is prime or not.

# import os

def enternum():
    test = int(input("Enter a number: "))
    checkprime(test)


def checkprime(test):

    if test == 1:
        print("The number is neither prime or composite.!")
    elif test == 2:
        print("The only even number which is prime!")
    elif test > 2:
        ghetto = int(test / 2)
        for i in range(2, ghetto + 1):
            if test % i == 0:
                i += 1
                print("Not a prime number!")
                break
            else:
                print("Prime number!")
                break

    flag = input("Want to try again? Y/N : ").lower()
    if flag == 'y':
        # os.system('cls')
        enternum()
    else:
        exit()


def mainstart():
    check = int(input("Enter 1 to check the number is prime or not. Press 2 to quit ::: "))
    if check == 1:
        enternum()
    elif check == 2:
        quit()
    else:
        print("Invalid Input. Try again.")

mainstart()

 

Day 11: And it continues with a list question again!

# Generate two random lists for different lengths
# and write a program that returns a list that contains only the elements
# that are common between the lists (without duplicates).
# Make sure your program works on two lists of different sizes.

import random

test1 = int(input("Enter the length of the first array: "))
test2 = int(input("Enter the length of the second array: "))

a = [random.randint(0, 100) for i in range(test1)]
b = [random.randint(0, 100) for i in range(test2)]
print(a, b)
c = print([i for i in a if i in b])

Lessons learned:

  1. Getting random numbers in your list makes it tough to find a common element in both the list with such a large data pool.
  2. You can literally shove the entire condition in one single line of code to find unique elements from both the lists.
  3. You cannot append the list at the end of the condition. Here, it meant printing the values in c. I was doing ==> c = print[for i in a if i in b c.append/c] <== which is not the correct method. Apparently it shows invalid syntax with expression required. Need to figure this out.