hacker-rank | min-max sum of array

find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

Example:
arr = [1,3,5,7,9]

The minimum sum is 1+3+5+7 = 16 and the maximum sum is 3+5+7+9 = 24. The function prints

16 24

Output Format
Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32-bit integer.)

Sample Input
1 2 3 4 5

Sample Output
10 14

Explanation:

The numbers are 1, 2, 3, 4, and 5. Calculate the following sums using four of the five integers:

  • Sum everything except 1, the sum is 1+2+3+4+5 = 14.
  • Sum everything except 2, the sum is 1+3+4+5 = 13.
  • Sum everything except 3, the sum is 1+2+4+5 = 12.
  • Sum everything except 4, the sum is 1+2+3+5 = 11.
  • Sum everything except 5, the sum is 1+2+3+4 = 10.

From the above calculation, 10 is the minimum and 14 is maximum.

Code language => Python

Solutions:

arr = [1,3,5,7,9]

def sumOfarray(arry):
    s = 0
    l = len(arry)
    for x in range(0,l):
        s =s+ arry[x]
    return s


def findminandmax(arr):
    sumOfarr = []
    for i in range(0, len(arr)):
        a  = arr[:]
        a.pop(i)
        sumOfarr.append(sumOfarray(a))
    return print(str(min(sumOfarr)) + " "+ str(max(sumOfarr)))

findminandmax(arr)

###output###
# 16 24

Note: we use a deep clone([:]) or deep copy for changing an array without affecting previous array values.

Example for deep clone:
1st case without deep clone

# Example for deep clone:
a = [5, 2]
b  =  a
b[0] = 100
print(a)
###output###
#[100 ,2]

2nd case with a deep clone [:]

# if we dont want to change variable a, then
a = [5,2]
b = a[:]
b[0] = 100
print(a)
###output###
#[5,2]

hacker-rank | print staircase right aligned with space and hash

Staircase detail

This is a staircase of size: n = 4

#
##
###
####

Note: Right-aligned #

Its base and height are both equal to n. It is drawn using # symbols and spaces. The last line is not preceded by any spaces.

Query: Write a program that prints a staircase of size n.

Function Description
The staircase has the following parameter(s):

int n: an integer
Print a staircase as described above.

Input Format
A single integer, n, denoting the size of the staircase.

Code language => Python

Solutions:

def staircase(n):
    l = n
    for x in range(0,l):
        ns = l-x -1
        print(ns * " "+("#")*(x+1))

staircase(6)

# output
     #
    ##
   ###
  ####
 #####
######

Note:
In python, we can multiply a string. eg,
=> “ab” * 2
=> abab
From above we can multiply the “ab” 2 times. So, we use the same concept to print space.

hacker-rank | calculate ratios of positive, negative, and zero elements

Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with 6 places after the decimal.


Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with an absolute error of up to 10^4 are acceptable.

Example
arr = [1, 1, 0, -1, -1]
There are n= 5 elements, two positive, two negative, and one zero. Their ratios are (2/5) = 0.400000 , (2/5) = 0.400000 and (1/5) = 0.200000. Results are printed as each in new lines:
0.400000
0.400000
0.200000

Coding language => Python
Coding logic => own logic

Solutions:

arr = [-4, 3, -9, 0, 4, 1]

 
# iterating each number in list
def findcount(numbers):
    pos_count, neg_count, zero_count = 0, 0, 0
    for num in numbers:
        # checking condition
        if num > 0:
            pos_count += 1
        elif num == 0:
            zero_count += 1
        elif num < 0:
            neg_count += 1
    return [pos_count, neg_count, zero_count]

def plusMinus(arr):
    l = len(arr)
    ratiolist = findcount(arr) 
    ratioOfPositive = ratiolist[0] / l
    ratioOfNegative = ratiolist[1] / l
    ratioOfZero = ratiolist[2] / l
    print(format(ratioOfPositive,'.6f' )+"\n"+ format(ratioOfNegative,'.6f' )+"\n"+ format(ratioOfZero,'.6f' ))

plusMinus(arr)

OUTPUT:
0.400000
0.400000
0.200000

NOTE: python print float digit with 6 decimal point
=> format(‘2′,’.6f’)
=> 2.000000

find factorial of a number in python simple way

find factorial in python easy way only 5 lines

Coding Style = my style of coding

Coding language = python

def findFactorial(num):
    a = 1
    for x in range(0, num):
       a = a * (num -x)
    return a
print(findFactorial(5))

# 5! * 4! * 3! * 2! * 1!
# output : 
# 120

Explanation:
for x in range(0, 5)
Already set a = 1, so

First loop
=> a = 1 * (5 – 0)
=> a = 5

Second loop
=> a = 5 * (5 – 1)
=> a = 5 * 4
=> a = 20

Third loop
=> a = 20 * (5 – 2)
=> a = 20 * 3
=> a = 60

Fourth loop
=> a = 60 * (5 – 3)
=> a = 60 * 2
=> a = 120

Fourth loop
=> a = 120 * (5 – 4)
=> a = 120 * 1
=> a = 120
After that x range is now 4, we set only in the range between 0 to 5
Now loop ended. So we print( findFactorial(5) ) => its return answer 120.

Hope this logic will help you to understand the factorial concept in programming. Thank you for reading!



Python Strings | tutorial 4

How to add single quotes, double quotes, or both quotes in the python strings?

Example:

course = "Python's for everyone"
print(course)
new_course = 'Python for "EveryOne"'
print(new_course)
email = '''
Hi John!,

Welcome to helperscript to learn Python's for "Everyone"

Thank you,
Support Team
'''
print(email)
The output of String declaration – python 3

Triple quotes (”’Python for “Everyone””’) – Three single quotes from the start and three single quotes from the end. This type of string escapes all the symbols in the string.

Split string into an array (or) Split the string in python

Python string starts index with zero(0).

Example: course variable has string “Python for Everyone”

Course = ‘Python for Everyone’

Get the first character of a string in python

course[0]   

Get the second character of a string in python

course[1]  

Get the last character of a string in python

course[-1]

Get the last second character of a string in python

course[-2]

Get the first three character of a string in python

course[0:3]

Remove the first character and remove the last 3 characters of a string in python

course[1:-3]

Remove the character after 6 index

course[:6]

Remove the first 6 characters in the string

course[6:]

Clone or copy the string

course[:]

Code: 

# strings
course = 'Python for Everyone'
print(course);
print('course[0] = ' + course[0])
print('course[1] = ' + course[1])
print('course[-1] = ' + course[-1])
print('course[-2] = ' + course[-2])
print('course[0:3] = ' + course[0:3])
print('course[1:-3] = ' + course[1:-3])
print('course[:5] = ' + course[:6])
print('course[6:] = ' + course[6:])
print('course[:] = ' + course[:])

OUTPUT:

String Concatenation

Two ways to concat the string dynamically.

Normal way – firstname +’ ’+ lastname +’ is a coder’
Format way – f‘{firstname} {lastname} is a code’

f – prefix with f define a formatted string

Code:

string concatenation in python

Python strings method

Let,
course = ‘Python for Beginners’

# find the length of string
len(course)

# convert uppercase
course.upper()

# convert lowercase
course.lower()

# convert first character uppercase in each word
course.title()

# find an index of character or sequence of character.

 Python find() method is case sensitive.

print(course.find(‘P’))  # gives index of capital P
print(course.find(‘p’))  # return -1 if not present. 
print(course.find(‘Beginners’))

# Replace a character
course.replace(‘P’, ‘J’)

# Replace a sequence of character
course.replace(‘Python’, ‘Angular’)

# find a string contains in the existing string(case sensitive)
‘Python’ in course

App.py

course = 'Python for Beginners'
# find the length of string
print(len(course))
# convert uppercase
print(course.upper())
# convert lowercase
print(course.lower())
# convert first character uppercase in each word
print(course.title())
# find index of character or sequence of character
print(course.find('P'))  # capital
print(course.find('p'))  # small letter
print(course.find('Beginners'))
# Replace a character
print(course.replace('P', 'J'))
# Replace a sequence of character
print(course.replace('Python', 'Angular'))
# find a string contains in existing string
print('Python' in course) # gives boolean output either True or False
String Methods in python 3

In Next article, we see about Operators in Python.

PYTHON variables | tutorial 3

Python is a case sensitive language. So when you define a variable you should consider the uppercase and lowercase.

eg: price = 10 is different to PRICE = 10

Important Variable Types and Declaration

price = 10
# price variable type is INTEGER
# price is an identifier for variable and initialised with the value 10

update_price = 20.5
# update_price variable type is FLOAT

is_published = True
# is_published variable type is BOOLEAN
# either True or False (case sensitive first letter should be capital)

name = 'Jasim'
# name variable type is STRING

# – is a comment line. Python interpreted not read this line.

Let’s do one small task.
Variable Declaration Task: We check in a patient named John Toe. He’s 20 years old and is a new patient.

name = 'John Toe'
Age = 20
is_new_patient = True

As of now we successfully learn how to declare the variable in python. Next, we learn about how to get input from users.

Instead of print() method use input() method to get the input from the user.

Filename: app.py

name = input('What is your name? ')
print('Hey! ' + name)
In your terminal, interpreted python will wait for your input. In my case, I type John Carter and then hit enter.

Task 2: Ask two questions – Person’s name and his favorite color. Print the output like “John Toe like violet”.

name = input('What is your name? ')
Color = input('what is your favourite color? ')
print(name + ' like ' + color);
The output of program – python input/print

Type conversion

Type conversion is used to define a variable for calculation. If the number is in string format we need to convert the number string into the integer type.

Example:

birth_year = input('Your birth year? ')
print(type(birth_year))
age = 2020 - birth_year
print('Your age is ' + age)
You will get an error – TypeError: Unsupported operand type(S) for int and str

You get input from the terminal 1994 and the type of 1994 is string identified with the use of type() method.

You get an error in line 20 in the app.py file. It will be shown in the terminal due to the type differentiation. So how to solve this problem. We need to convert the type from string to integer.

How to convert the string to integer

int() – method is used to convert the typed string to an integer.
str() – method is used to convert the integer type to string type.

Solution:

birth_year = input('Your birth year? ')
print(type(birth_year))
age = 2020 - int(birth_year)
print('Your age is ' + str(age))
output: Type conversion example

In the next article let see the strings in python. Go the next continuation on the menu.

Basics of python tutorial 2

Open your PyCharm or your favorite IDE. Click to create a new project and name your project.

Give your project name and check the base interpreter has the current version. If you need another version, you can select the other version from the list.

Create a first python program

Name your file. In my case app.py

Now let’s start to learn the code first.

How to console or print the value in the python

file name: app.py

print('Hi! welcome to helperscript');

print(data) => print function helps to print or console in terminal output. It is used to identify whether the data passed are correct or incorrect.

data => you can pass data that you want to output. When your data is a string. String declaration with a single quote or either double quote.

Eg: print(“hello”) is equal to print(‘hello’)
Then Run the app.py file from the menu Run. It will show configuration settings. As of now we just run the file. So just click on the app.

After Run the app.py file. The below terminal will open and show the output like below.

output in console python

Python code gets executed line by line from the top.

Print the string with the multiplication

file name: app.py

print('Hi! welcome to helperscript')
print('*' * 5)
output of print(‘*’ * 5)

In python, the String data type can be generated and printed multiple times with an asterisk.

So the python is powerful for AI, Automation, desktop application, and web application. 

Let us see more new topics in python in the next article. Go to the menu of Python and find the next tutorial for continuation…

Python 3 tutorial step by step learning through free courses

INTRODUCTION TO PYTHON 3

Python is one of the most popular languages nowadays.

Python has the ability to do

  1. Automation
  2. AI (Artificial Intelligence)
  3. Applications
  4. Websites

We talk about all the core concepts in python and then we build three(3) python projects together.

BUILD WEB APPLICATION

Django administration

HOW TO USE 1000 OF SPREADSHEET IN MIN 100 SECONDS  WITH CHARTS

CHARTS IN SPREADSHEET USING PYTHON

Let’s start the course for the absolute beginners.

INSTALL PYTHON

HOW TO DOWNLOAD AND INSTALL PYTHON ON YOUR COMPUTER

  1. Go to python.org
  2. Click on downloads
  3. Click the Download button for the latest version

In windows simply click and open the downloaded file. Make sure you check Add path to the variable.

For Mac, Just continue and Agree with the license agreement and install it.

Install python in mac

Next, we are going to install a code editor. PyCharm (https://jetbrains.com/pycharm) is one of the best code editors for python. It fully depends on you. You can use another editor too.

Download and install pyCharm on your computer depends on your OS.

Windows => click next => next => and install

Mac => drag and drop the pyCharm to the application to install.

Choose your theme, Most of them use Dracula or blacky themes to protect their eyes. Now open your pyCharm application.

Congratulations, you are now successfully downloading and installing everything for python to learn.

Go to the python menu on top and see the continuation tutorial in the python.