Sunday 29 September 2019

Evoting

pragma solidity ^0.4.21;
contract Election{
    struct Canditate{
        string name;
        uint voteCount;
    }
    struct Voter{
        bool authorized;
        bool voted;
        uint vote;
    }
    address public owner;
    string public electionName;
    
    mapping(address => Voter) public Voters;
    Canditate[] public Canditates;
    uint public totalVotes;
    
    modifier ownerOnly(){
        require(msg.sender == owner);
        _;
    }
    function Election(string _name) public {
        owner = msg.sender;
        electionName = _name;
    }
    function getNumberCandidates() public view returns(uint) {
        return Canditates.length;
    }
    function addCandidate(string _name) ownerOnly public {
        Canditates.push(Canditate(_name,0));
    }
    function authorize(address _person) ownerOnly public {
        Voters[_person].authorized = true;
    }
    function vote(uint _voterIndex) public {
        require(!Voters[msg.sender].voted);
        require(Voters[msg.sender].authorized);
        
        Voters[msg.sender].vote = _voterIndex;
        Voters[msg.sender].voted = true;
         Canditates[_voterIndex].voteCount += 1;
         totalVotes += 1;
    }
    
    function end() ownerOnly public {
        selfdestruct(owner);
    }
    

Blockchain 3

pragma solidity ^0.4.0;
contract SimpleStorage{
    uint a;
    uint shop_1=0;
    uint shop_2=0;
    function initial( uint balu)public{
        a = balu;
    }
     function Shop1( uint balu)public{
        a = a-balu;
        shop_1=shop_1+balu;
    }
     function Shop2(uint balu)public{
          a = a-balu;
          shop_2=shop_2+balu;
    }
     function add(uint balu)public{
          a = a+balu;
    }
    function balance()public constant returns(uint){
        return a;
    }
     function shop_1balance()public constant returns(uint){
        return shop_1;
    } function shop_2balance()public constant returns(uint){
        return shop_2;
    }
    
}

Blockchain 2

pragma solidity ^0.4.0;
contract SimpleStorage{
    uint a;
    function initial( uint balu)public{
        a = balu;
    }
     function Shop1( uint balu)public{
        a = a-balu;
    }
     function Shop2(uint balu)public{
          a = a-balu;
    }
     function add(uint balu)public{
          a = a+balu;
    }
    function balance()public constant returns(uint){
        return a;
    }}

Blockchain Addition

pragma solidity ^0.4.0;
contract AddInteger{
  uint private c;
function addition(uint _a, uint _b) public constant returns(uint)
  {
     c = _a+_b;
     return c;
  } }

Saturday 28 September 2019

Python Blockchain

import datetime
import hashlib

class Block:
    blockNo = 0
    data = None
    next = None
    hash = None
    nonce = 0
    previous_hash = 0x0
    timestamp = datetime.datetime.now()

    def __init__(self, data):
        self.data = data

    def hash(self):
        h = hashlib.sha256()
        h.update(
        str(self.nonce).encode('utf-8') +
        str(self.data).encode('utf-8') +
        str(self.previous_hash).encode('utf-8') +
        str(self.timestamp).encode('utf-8') +
        str(self.blockNo).encode('utf-8')
        )
        return h.hexdigest()

    def __str__(self):
        return "Block Hash: " + str(self.hash()) + "\nBlockNo: " + str(self.blockNo) + "\nBlock Data: " + str(self.data) + "\nHashes: " + str(self.nonce) + "\n--------------"

class Blockchain:

    diff = 20
    maxNonce = 2**32
    target = 2 ** (256-diff)

    block = Block("Genesis")
    dummy = head = block

    def add(self, block):

        block.previous_hash = self.block.hash()
        block.blockNo = self.block.blockNo + 1

        self.block.next = block
        self.block = self.block.next

    def mine(self, block):
        for n in range(self.maxNonce):
            if int(block.hash(), 16) <= self.target:
                self.add(block)
                print(block)
                break
            else:
                block.nonce += 1

blockchain = Blockchain()

for n in range(10):
    blockchain.mine(Block("Block " + str(n+1)))

while blockchain.head != None:
    print(blockchain.head)
    blockchain.head = blockchain.head.next

Python UDF


# This function adds two numbers
def add(x, y):
   return x + y

# This function subtracts two numbers
def subtract(x, y):
   return x - y

# This function multiplies two numbers
def multiply(x, y):
   return x * y

# This function divides two numbers
def divide(x, y):
   return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user
choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("Invalid input")

Thursday 26 September 2019

DT

install.packages("party") 

library(party)

input= readingSkills[c(1:105),]

output = ctree(
  nativeSpeaker ~ age + shoeSize + score,
  data = input)

plot(output)

Wednesday 25 September 2019

Datasetlink

https://drive.google.com/open?id=1oD1mFi4zmqz5xGuCJ7_OdUKZgW5fekct

Tuesday 24 September 2019

DT - R

install.packages("party") 

library(party)

input= readingSkills[c(1:105),]

output = ctree(
  nativeSpeaker ~ age + shoeSize + score,
  data = input)

plot(output)

Monday 23 September 2019

LM- R


x = c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)

y = c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)

relation = lm(y~x)
________________________________________



# Find weight of a person with height 170.
a = data.frame(x = 170)
result =  predict(relation,a)
print(result)

Saturday 21 September 2019

Azure IOT HUB

https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-live-data-visualization-in-web-apps#code-try-2

https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-raspberry-pi-kit-node-get-started

https://azure-samples.github.io/raspberry-pi-web-simulator/#Getstarted

Friday 20 September 2019

link

https://azure.microsoft.com/en-us/services/cognitive-services/directory/vision/

MS API

#Copyright (c) Microsoft Corporation. All rights reserved.
#Licensed under the MIT License.

# -*- coding: utf-8 -*-

import http.client, urllib.parse, json

# **********************************************
# *** Update or verify the following values. ***
# **********************************************

# Replace the subscriptionKey string value with your valid subscription key.
subscriptionKey = 'a8ad3c49b5224ff382cc138a0a52862b'

host = 'api.cognitive.microsoft.com'
path = '/bing/v7.0/Suggestions'

mkt = 'en-US'
query = 'BML'

params = '?mkt=' + mkt + '&q=' + query

def get_suggestions ():
    "Gets Autosuggest results for a query and returns the information."

    headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
    conn = http.client.HTTPSConnection(host)
    conn.request ("GET", path + params, None, headers)
    response = conn.getresponse ()
    return response.read ()

result = get_suggestions ()
print (json.dumps(json.loads(result), indent=4))

Thursday 19 September 2019

Random Forest

#Import scikit-learn dataset library
from sklearn import datasets

#Load dataset
iris = datasets.load_iris()

# print the label species(setosa, versicolor,virginica)
print(iris.target_names)

# print the names of the four features
print(iris.feature_names)

# print the iris data (top 5 records)
print(iris.data[0:5])

# print the iris labels (0:setosa, 1:versicolor, 2:virginica)

print(iris.target)

############################################

# Creating a DataFrame of given iris dataset.
import pandas as pd
data=pd.DataFrame({
    'sepal length':iris.data[:,0],
    'sepal width':iris.data[:,1],
    'petal length':iris.data[:,2],
    'petal width':iris.data[:,3],
    'species':iris.target
})
data.head()

# Import train_test_split function
from sklearn.model_selection import train_test_split

X=data[['sepal length', 'sepal width', 'petal length', 'petal width']]  # Features
y=data['species']  # Labels

# Split dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # 70% training and 30% test

#Import Random Forest Model
from sklearn.ensemble import RandomForestClassifier

#Create a Gaussian Classifier
clf=RandomForestClassifier(n_estimators=100)

#Train the model using the training sets y_pred=clf.predict(X_test)
clf.fit(X_train,y_train)

y_pred=clf.predict(X_test)
#############################################

#Import scikit-learn metrics module for accuracy calculation
from sklearn import metrics
# Model Accuracy, how often is the classifier correct?
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))

clf.predict([[3, 5, 4, 2]])

##########################

from sklearn.ensemble import RandomForestClassifier

#Create a Gaussian Classifier
clf=RandomForestClassifier(n_estimators=100)

#Train the model using the training sets y_pred=clf.predict(X_test)
clf.fit(X_train,y_train)
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
            max_depth=None, max_features='auto', max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=1,
            oob_score=False, random_state=None, verbose=0,
            warm_start=False)
import pandas as pd
feature_imp = pd.Series(clf.feature_importances_,index=iris.feature_names).sort_values(ascending=False)
feature_imp

######################

import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# Creating a bar plot
sns.barplot(x=feature_imp, y=feature_imp.index)
# Add labels to your graph
plt.xlabel('Feature Importance Score')
plt.ylabel('Features')
plt.title("Visualizing Important Features")
plt.legend()
plt.show()
#######################

# Import train_test_split function
from sklearn.cross_validation import train_test_split
# Split dataset into features and labels
X=data[['petal length', 'petal width','sepal length']]  # Removed feature "sepal length"
y=data['species']                                     
# Split dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.70, random_state=5) # 70% training and 30% test

#####################

from sklearn.ensemble import RandomForestClassifier

#Create a Gaussian Classifier
clf=RandomForestClassifier(n_estimators=100)

#Train the model using the training sets y_pred=clf.predict(X_test)
clf.fit(X_train,y_train)

# prediction on test set
y_pred=clf.predict(X_test)

#Import scikit-learn metrics module for accuracy calculation
from sklearn import metrics
# Model Accuracy, how often is the classifier correct?
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))







Wednesday 18 September 2019

GraphViz Details

https://graphviz.gitlab.io/_pages/Download/Download_windows.html
___________________________________________

Install GraphViz if you haven't already (I used the MSI download)

Get the path for gvedit.exe (for me it was "C:\Program Files (x86)\Graphviz2.34\bin\")
Add this path to the computer's PATH

One way to get to environment settings to set your path is to click on each of these button/menu options: start->computer->system properties->advanced settings->environment variables
Click Edit User path
Add this string to the end of your Variable value list (including semicolon): ;C:\Program Files (x86)\Graphviz2.34\bin
Click OK

Restart your Python IDE


ANN




import numpy as np
feature_set = np.array([[0,1,0],[0,0,1],[1,0,0],[1,1,0],[1,1,1]])
labels = np.array([[1,0,0,1,1]])
labels = labels.reshape(5,1)


# In[3]:


labels


# In[8]:


#define hyper parameters for our neural network

np.random.seed(42)  #random.seed function so that we can get the same random values whenever the script is executed.
weights = np.random.rand(3,1)
bias = np.random.rand(1)
lr = 0.05


# In[9]:


weights  #Return a sample (or samples) from the “standard normal” distribution( “normal” (Gaussian) distribution of mean 0 and variance 1)


# In[10]:


bias #Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1)


# In[11]:


lr # learning rate


# In[12]:


def sigmoid(x):    #activation function is the sigmoid function
    return 1/(1+np.exp(-x))


# In[13]:


def sigmoid_der(x):    #calculates the derivative of the sigmoid function
    return sigmoid(x)*(1-sigmoid(x))


# In[14]:


#train our neural network that will be able to predict whether a person is obese or not.

# An epoch is basically the number of times we want to train the algorithm on our data.
#We will train the algorithm on our data 20,000 times. The ultimate goal is to minimize the error.

for epoch in range(20000):
    inputs = feature_set

#Here we find the dot product of the input and the weight vector and add bias to it.

    # feedforward step1
    XW = np.dot(feature_set, weights) + bias
 
#We pass the dot product through the sigmoid activation function

    #feedforward step2
    z = sigmoid(XW)
 
#The variable z contains the predicted outputs. The first step of the backpropagation is to find the error.

    # backpropagation step 1
    error = z - labels

    print(error.sum())

    # backpropagation step 2
    dcost_dpred = error
    dpred_dz = sigmoid_der(z)
 
#Here we have the z_delta variable, which contains the product of dcost_dpred and dpred_dz.
#Instead of looping through each record and multiplying the input with corresponding z_delta,
#we take the transpose of the input feature matrix and multiply it with the z_delta.
#Finally, we multiply the learning rate variable lr with the derivative to increase the speed of convergence.

    z_delta = dcost_dpred * dpred_dz

    inputs = feature_set.T
    weights -= lr * np.dot(inputs, z_delta)

    for num in z_delta:
        bias -= lr * num


# In[15]:


#You can see that error is extremely small at the end of the training of our neural network.
#At this point of time our weights and bias will have values that can be used to detect whether a person is diabetic or not,
#based on his smoking habits, obesity, and exercise habits.

#TEST : suppose we have a record of a patient that comes in who smokes, is not obese, and doesn't exercise.
#Let's find if he is likely to be diabetic or not. The input feature will look like this: [1,0,0].

single_point = np.array([1,0,0])
result = sigmoid(np.dot(single_point, weights) + bias)
print(result)


# In[ ]:


#You can see that the person is likely not diabetic since the value is much closer to 0 than 1.


# In[16]:


#let's test another person who doesn't, smoke, is obese, and doesn't exercises. The input feature vector will be [0,1,0]

single_point = np.array([0,1,0])
result = sigmoid(np.dot(single_point, weights) + bias)
print(result)


# In[18]:


#value is very close to 1, which is likely due to the person's obesity.
#Multiply the result by 100 percent to convert the accuracy to a percentage. For our thermometer example:
#Relative accuracy = Accuracy x 100 percent = 0.968 x 100 percent = 96.8 percent

A=0.00707584 * 100
B=0.99837029 * 100
print(A)
print(B)

Log Reg

#import pandas
import pandas as pd
# import required modules
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#%matplotlib inline
col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']
# load dataset
pima = pd.read_csv("diabetes.csv", header=1, names=col_names)
pima.head()

#split dataset in features and target variable
feature_cols = ['pregnant', 'insulin', 'bmi', 'age','glucose','bp','pedigree']
X = pima[feature_cols] # Features
y = pima.label # Target variable

# split X and y into training and testing sets
from sklearn.cross_validation import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=0)


# import the class
from sklearn.linear_model import LogisticRegression

# instantiate the model (using the default parameters)
logreg = LogisticRegression()

# fit the model with data
logreg.fit(X_train,y_train)

y_pred=logreg.predict(X_test)

##############################################3
# import the metrics class
from sklearn import metrics
cnf_matrix = metrics.confusion_matrix(y_test, y_pred)
print(cnf_matrix)
###########################################


class_names=[0,1] # name  of classes
fig, ax = plt.subplots()
tick_marks = np.arange(len(class_names))
plt.xticks(tick_marks, class_names)
plt.yticks(tick_marks, class_names)
# create heatmap
"""data – 2D dataset that can be coerced into an ndarray. If a Pandas DataFrame is provided, the index/column information will be used to label the columns and rows.
annot – an array of same shape as data which is used to annotate the heatmap.
cmap – a matplotlib colormap name or object. This maps the data values to the color space.
fmt – string formatting code to use when adding annotations.
linewidths – sets the width of the lines that will divide each cell."""

sns.heatmap(pd.DataFrame(cnf_matrix), annot=True, cmap="YlGnBu" ,fmt='g')
ax.xaxis.set_label_position("top")
#position : {'top', 'bottom'}

plt.tight_layout()
plt.title('Confusion matrix', y=1.1)
plt.ylabel('Actual label')
plt.xlabel('Predicted label')

print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
print("Precision:",metrics.precision_score(y_test, y_pred))
print("Recall:",metrics.recall_score(y_test, y_pred))

"""Precision: Precision is about being precise, i.e.,
how accurate your model is. In other words, you can say,
when a model makes a prediction, how often it is correct.
In your prediction case, when your Logistic Regression model
predicted patients are going to suffer from diabetes,
that patients have 76% of the time.

Recall: If there are patients who have diabetes in the test set
and your Logistic Regression model can identify it 58% of the time.

"""
"""Receiver Operating Characteristic(ROC) curve is a plot
of the true positive rate against the false positive rate.
It shows the tradeoff between sensitivity and specificity."""

y_pred_proba = logreg.predict_proba(X_test)[::,1]
fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)
auc = metrics.roc_auc_score(y_test, y_pred_proba)
plt.plot(fpr,tpr,label="data 1, auc="+str(auc))
plt.legend(loc=4)
plt.show()

"""AUC score for the case is 0.86. AUC score 1 represents perfect classifier,
and 0.5 represents a worthless classifier."""








GUI

from pandas import DataFrame
from sklearn import linear_model
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

Stock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
                'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
                'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
                'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]       
                }

df = DataFrame(Stock_Market,columns=['Year','Month','Interest_Rate','Unemployment_Rate','Stock_Index_Price'])

X = df[['Interest_Rate','Unemployment_Rate']].astype(float) # here we have 2 input variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example.Alternatively, you may add additional variables within the brackets
Y = df['Stock_Index_Price'].astype(float) # output variable (what we are trying to predict)

# with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)


# tkinter GUI
root= tk.Tk()

canvas1 = tk.Canvas(root, width = 500, height = 300)
canvas1.pack()

# with sklearn
Intercept_result = ('Intercept: ', regr.intercept_)
label_Intercept = tk.Label(root, text=Intercept_result, justify = 'center')
canvas1.create_window(260, 220, window=label_Intercept)

# with sklearn
Coefficients_result  = ('Coefficients: ', regr.coef_)
label_Coefficients = tk.Label(root, text=Coefficients_result, justify = 'center')
canvas1.create_window(260, 240, window=label_Coefficients)


# New_Interest_Rate label and input box
label1 = tk.Label(root, text='Type Interest Rate: ')
canvas1.create_window(100, 100, window=label1)

entry1 = tk.Entry (root) # create 1st entry box
canvas1.create_window(270, 100, window=entry1)

# New_Unemployment_Rate label and input box
label2 = tk.Label(root, text=' Type Unemployment Rate: ')
canvas1.create_window(120, 120, window=label2)

entry2 = tk.Entry (root) # create 2nd entry box
canvas1.create_window(270, 120, window=entry2)


def values():
    global New_Interest_Rate #our 1st input variable
    New_Interest_Rate = float(entry1.get())
   
    global New_Unemployment_Rate #our 2nd input variable
    New_Unemployment_Rate = float(entry2.get())
   
    Prediction_result  = ('Predicted Stock Index Price: ', regr.predict([[New_Interest_Rate ,New_Unemployment_Rate]]))
    label_Prediction = tk.Label(root, text= Prediction_result, bg='orange')
    canvas1.create_window(260, 280, window=label_Prediction)
   
button1 = tk.Button (root, text='Predict Stock Index Price',command=values, bg='orange') # button to call the 'values' command above
canvas1.create_window(270, 150, window=button1)


#plot 1st scatter
figure3 = plt.Figure(figsize=(5,4), dpi=100)
ax3 = figure3.add_subplot(111)
ax3.scatter(df['Interest_Rate'].astype(float),df['Stock_Index_Price'].astype(float), color = 'r')
scatter3 = FigureCanvasTkAgg(figure3, root)
scatter3.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
ax3.legend()
ax3.set_xlabel('Interest Rate')
ax3.set_title('Interest Rate Vs. Stock Index Price')

#plot 2nd scatter
figure4 = plt.Figure(figsize=(5,4), dpi=100)
ax4 = figure4.add_subplot(111)
ax4.scatter(df['Unemployment_Rate'].astype(float),df['Stock_Index_Price'].astype(float), color = 'g')
scatter4 = FigureCanvasTkAgg(figure4, root)
scatter4.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
ax4.legend()
ax4.set_xlabel('Unemployment_Rate')
ax4.set_title('Unemployment_Rate Vs. Stock Index Price')

root.mainloop()

Tuesday 17 September 2019

List Tuple and Dic


list = [ ‘xyz', 123, 1.23, ‘RAM', 17.5 ]
tinylist = [123, ‘RAM']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists
list.append(“Manish”) #Applicable
print(“list[3:] = ", list[3:])  







tuple = (‘xyz', 123, 1.23, ‘RAM', 17.5 )
tinytuple = (123, ‘RAM‘)
print(tuple) # Prints complete list
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(tuple[2:]) # Prints elements starting from 3rd element
print(tinytuple * 2) # Prints list two times
print (tuple + tinytuple) # Prints concatenated lists
tuple.append(‘Manish’) # Not Applicable





dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': ‘RAM','code:8989:, 'dept': ‘IT'}
print(dict['one']) # Prints value for 'one' key
print(dict[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values

String Python


str = 'Hello World!’
print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST") # Prints concatenated string
print(str[:-2])    # Hello Worl
print(str[::-1])  # Reverse   !dlroW olleH
print(str[::-2])  # Alternative reverse    !lo le
len(str) # 12 including space
str.count(' ')   # Space Count