Search This Blog

Assignment 01 - Complete Java + DSA + Interview Preparation Course - Kunal Kushwaha

 

Assignment of Flow of Program - Flowcharts & Pseudocode - Video 02Kunal Kushwaha ]

Create flowchart and pseudocode for the following:

1. Input a year and find whether it is a leap year or not.

    Solution: 

Flow Chart

Pseudocode

1. Start
2. Input year in type int
3. if year%4==0 and year%100!=0 or year%400==0:
          output: Leap Year
    else:
          output: Non Leap Year
4. Stop

2. Take two numbers and print the sum of both.
    
    Solution: 

Flow Chart

Pseudocode

1. Start
2. Input num1 & num2 in type int
3. sum=num1+num2
4. output: sum
5. Stop


3. Take a number as input and print the multiplication table for it.
   
    Solution: 

Flow Chart

Pseudocode

1. Start
2. Input num in type int
3. multiplier=1
    while multiplier!=11:
            output: num*multiplier
             multiplier=multiplier+1
     end while
5. Stop


4. Take 2 numbers as inputs and find their HCF and LCM.

    Solution: Yet to do.

Flow Chart


Pseudocode


5. Keep taking numbers as inputs till the user enters ‘x’, after that print sum of all.

    Solution: 

Flow Chart





Pseudocode

1. Start
2. num = [ ] , add = 0
    while True:
          input s
          if s=='x' or s=='X':
                  for i in s:
                       add=add+int(i)
                   end for
                   output add
                    exit
           else:
                   num.append(s)
     end while
3. Stop



Techgig Geek Goddess Screening Round Solution - Python

 



Oddia and Evenia are two friends who love strings and prime numbers. Although they have the same taste and like similar things, they are enemies when it comes to even and odd numbers. Oddia likes the odd numbers and Evenia likes the even numbers. They have a problem for you to solve.

A string S of lowercase letters will be provided and you have to figure out if the given string is Prime String or not. The index starts at 1.

Prime String: A string is considered a prime string only if the absolute difference between the sum of odd indexed letters and even indexed letters is completely divisible by any of the odd prime numbers less than 10.

Note: For calculations, consider the ASCII value of lowercase letters.

Example:

String, S = abcdef

Summation of Odd Indexed letters, O = a + c + e = 97 + 99 + 101 = 297

Summation of Even Indexed letters, E = b + d + f = 98 + 100 + 102 = 300

Absolute Difference = |O-E| = |297-300| = 3

This is completely divisible by 3 and leaves 0 as remainder. Thus, the given string is a Prime String.

If the string is prime string, print Prime String otherwise print Causal String. Can you solve it?


Input Format

The first line of input consists of the number of test cases, T

Next N lines each consist of a string, S.

Note: Read the input from the console.

Constraints

1<= T <=10

2<= |S| <=10000

|S| is the length of the string.


Output Format

For each test case, print Prime String if the string is prime string otherwise print Casual String.


Sample TestCase 1

Input

2

bbae

abcdef

Output

Casual String

Prime String

Explanation

Test Case 1: 


Sum of Odd indexed letters, O = 98+97 = 195

Sum of Even indexed letters, E = 98 + 101 = 199

Absolute Difference = |195-199| = 4

This is not divisible by any of the odd prime numbers. The given string is a Casual String.

----------------------------------------

Solution:

def check():

    
    num = int(input())

 

    for i in range(num):
        st = input()
        i = 0
        even_num = 0
        odd_num = 0
        for char in st:
            if i % 2 == 0:
                even_num+=ord(char)
            else:
                odd_num+=ord(char)
            i+=1
            
        ab_diff = abs(even-odd)
    
        if ab_diff % 3 == 0 or ab_diff % 5 == 0 or ab_diff % 7 == 0:
            print("Prime String")
        else:
            print("Casual String")

check()



Object Oriented Coffee Maker Machine : Python

 

Object Oriented Coffee Maker Machine : Python
Object Oriented Coffee 
Maker Machine
( Python Based ) 

The functionality given to the virtual coffee machine is a replica of our actual coffee machine. But, this oops-oriented coffee machine can only take order one out of latte/espresso/cappuccino.

The code is designed after determining 5 conditions to serve the coffee:

  • Turn On & Off the machine
  • Print the available quantity of the resources & money
  • Process the made payment by the user
  • Here, check out the given payment is ok?
  • Serve the coffee
Before solving the above-mentioned conditions, the modules containing these functionalities are imported. And the functionality of these modules can be understood from below given class's documentation:

MenuItem Class

Attributes:

        

  • name

(str) The name of the drink.

e.g. “latte”

  • cost

(float) The price of the drink.

e.g 1.5

  • ingredients

(dictionary) The ingredients and amounts required to make the drink.

e.g. {“water”: 100, “coffee”: 16}

Menu Class

Methods:

  • get_items()

Returns all the names of the available menu items as a concatenated string.

e.g. “latte/espresso/cappuccino”

  • find_drink(order_name)

Parameter order_name: (str) The name of the drinks order.

Searches the menu for a particular drink by name. Returns a MenuItem object if it exists, otherwise returns None.

CoffeeMaker Class

Methods:

  • report()

Prints a report of all resources.

e.g.

Water: 300ml

Milk: 200ml

Coffee: 100g

  • is_resource_sufficient(drink)

Parameter drink: (MenuItem) The MenuItem object to make.

Returns True when the drink order can be made, False if ingredients are insufficient.

e.g.

True

  • make_coffee(order)

Parameter order: (MenuItem) The MenuItem object to make.

Deducts the required ingredients from the resources.

MoneyMachine Class

Methods:

  • report()

Prints the current profit

e.g.

Money: $0

  • make_payment(cost)

Parameter cost: (float) The cost of the drink.

Returns True when payment is accepted, or False if insufficient.

e.g. False


Final Code Structure

1. Turn On & Off the machine

is_on=True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on =
False
2. Print the available quantity of the resources & money - The final report

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine


coffee = CoffeeMaker()
money = MoneyMachine()
menu = Menu()

is_on = True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on = False
elif choice == 'report':
money.report()
coffee.report()
3. & 4. Process the made payment by the user. Also, check out the given payment is ok?

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine


coffee = CoffeeMaker()
money = MoneyMachine()
# menuitem = MenuItem()
menu = Menu()
is_on=True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on = False
elif choice == 'report':
money.report()
coffee.report()
else:
drink = menu.find_drink(choice)
if coffee.is_resource_sufficient(drink):
if money.make_payment(drink.cost):
5. Serve the coffee

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine


coffee = CoffeeMaker()
money = MoneyMachine()
menu = Menu()

is_on = True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on = False
elif choice == 'report':
money.report()
coffee.report()
else:
drink = menu.find_drink(choice)
if coffee.is_resource_sufficient(drink):
if money.make_payment(drink.cost):
coffee.make_coffee(drink)
Thank You :)

Solution to Exploring Data Types TechGig - 02


Exploring Data Types TechGig

Exploring Data Types TechGig


The question asked to check out the data type of the user input. It was quite tricky as python by default converts the type of the input into type str. So, I was halfway blank like what approach to use.


Further, I googled & ended up with this article: How You Make Sure input() Is the Type You Want It to Be in Python Unluckily, it introduced me with nothing new concept but, gave me a path to go & explore libraries. And while looking out for them I discovered regex that is regular expressions in python and to this, I thought of adding exception handling.

Finally, trial & test lead me to a code that actually passed out all the test cases. Seriously, Exception handling is a wingman.

Also, keeping below mentioned five custom inputs in mind, I had been able to see the clear picture:

Custom Input 1: Hello Engineer Bae
Expected Output: This input is of type string.

Custom Input 2: 22.33
Expected Output: This input is of type Float.

Custom Input 3: 33
Expected Output: This input is of type Integer.

Custom Input 4: @@
Expected Output: This is something else.

Custom Input 5:             #space as input since, space is a character
Expected Output: This input is of type string.

Here we go. The code that is the answer to the exploring data types - day 02 question of techgig

Snake Water Gun Game - My Solution to CodewithHarry Snake Water Gun Game


This is an ancient game that is full of fun and is generally played between two players. Somewhat it is similar to Rock, Paper & Scissor.

Good Points

  1. This game can be played without the need for a second human opponent.
  2. The second opponent in this game will be a computer.
  3. This exercise is part of code with harry's Python Tutorial for Beginners
  4. This code is completely written by me.

How does this game work?

The game is developed for single-player only with easy & hard mode.

  1. Easy mode allows you to give a total of 10 chances to score better.
  2. Hard mode allows you to give a total of 5 chances to score better.

And the Rules are-

The game keeps running until you don't reach the last value of your selected mode(Easy or Hard).

1. Water will win from the gun, the gun will win from snake, the snake will 
win from water.
2. Out of user or computer whoever scores the highest, wins the match.
3. "Tie" is given if both of them chooses the same shape & no score is rewarded
to any player.
4. Scores are given on the basis of each chance's winner.


Final Code/Solution to Code with Harry's Project 1 - Snake, Water, Gun Game at Timestamp: 06:52:30
 
import random
import os


logo = '''
███ █   █ ███ █ █ ███   █   █ ███ ███ ███ ███   ███ █ █ █   █   ███ ███ █   █ ███ 
█   ██  █ █ █ █ █ █     █   █ █ █  █  █   █ █   █   █ █ ██  █   █   █ █ ██ ██ █   
 █  █ █ █ █ █ ██  ███   █ █ █ █ █  █  ███ ██    █   █ █ █ █ █   █   █ █ █ █ █ ███ 
  █ █  ██ ███ █ █ █     ██ ██ ███  █  █   █ █   █ █ █ █ █  ██   █ █ ███ █   █ █   
███ █   █ █ █ █ █ ███   █   █ █ █  █  ███ █ █   ███ ███ █   █   ███ █ █ █   █ ███ 
'''

# Generated Ascii art from here, https://ascii.co.uk/text & font is Maxiwi

snake = ''' 
      {0O}
      \__/
      /^/
     ( (             
     \_\_____
     (_______)
    (_________()Oo
'''

water='''

_____________________________________________
 -   ~~~       -    ----     -       -      -   
  ~    --     ~         ~    --       --  ``
---            ---          ---       / ~
     ----  ~     ----        ----      ~  / 
-----         -----         ----- /   '   '~    
  ~   .-~~-.      ~    ------     / ~   ~    
___________________________________________

'''

gun= '''
  .-.____________________.-.
     ___ _.' .-----.    _____________|======+
    /_._/   (      |   /_____________|      
      /      `  _ ____/                     
     |_      .\( \\                         
    .'  `-._/__`_// 
  .'       |""""'
 /        /
/        |
|        '
|         \
`-._____.-'
'''

end_game= False
easy=10
hard=5
user_score=0
computer_score=0


shapes = [snake, water , gun]


def shape_choice(shape):
    '''Allows to choose shape for a computer'''
    return random.choice(shape)


def game_decision(usr_choose_shape,computer_choose_shape,shapes,mode):
    '''Water will win from gun, gun will win from snake, snake will win from water.
    Snake--Water--Gun'''

    global user_score
    global computer_score

    if shapes[usr_choose_shape] == shapes[0] and computer_choose_shape == shapes[1]:
        print(f"This chance is won by YOU :)")
        user_score+=1
        print(f'\t Your Score: {user_score}')
        print(f"\t Computer's Score: {computer_score}")
        print(f" You're left with {mode} chance(s).")
        
    elif shapes[usr_choose_shape]==shapes[2] and computer_choose_shape == shapes[0]:
        print("This chance is won by YOU :)")
        user_score+=1
        print(f'\t Your Score: {user_score}')
        print(f"\t Computer's Score: {computer_score}")
        print(f" You're left with {mode} chance(s).")
        
    elif shapes[usr_choose_shape]==shapes[1] and computer_choose_shape == shapes[2]:
        print("This chance is won by YOU :)")
        user_score+=1
        print(f'\t Your Score: {user_score}')
        print(f"\t Computer's Score: {computer_score}")
        print(f" You're left with {mode} chance(s).")
    else:
        print('This chance is won by COMPUTER :(')
        computer_score+=1
        print(f'\t Your Score: {user_score}')
        print(f"\t Computer's Score: {computer_score}")
        print(f" You're left with {mode} chance(s).")
        



os.system('cls')
print(logo)
user=input("Choose mode: 'E' for easy & 'H' for hard: ").lower()

if user == 'E':
    print(f'\tYou have {easy} chances to win over your opponent.')
    mode=easy
else:
    print(f'\tYou have {hard} chances to win over your opponent.')
    mode=hard


def game(mode):
    
    global user_score
    global computer_score
    global easy
    global hard

    while mode!=0:

        
        # user and computer choice -> 
        

        usr_choose_shape = int(input("\n\tType 1 for Snake, 2 for Water & 3 for Gun: "))
        computer_choose_shape = shape_choice(shapes)

        

        os.system('cls')
        mode-=1

        print(logo)


        print(f"Your Choice: {shapes[usr_choose_shape-1]} ")
        
        print(f"Computer Choice: {computer_choose_shape}" )
        

        if shapes[usr_choose_shape-1] == computer_choose_shape:
            print("Nobody wins. It's a TIE!")
            print(f'\t Your Score: {user_score}')
            print(f"\t Computer's Score: {computer_score}")
            print(f" You're left with {mode} chance(s).")
            
        else:
            s=game_decision(usr_choose_shape-1,computer_choose_shape,shapes,mode )




        

    os.system('cls')
    print(logo)

    if user_score > computer_score:
        print(f"Your Final Score: 0{user_score}")
        print(f"Computer's Final Score: 0{computer_score}")
        print(f'Congratulations, you are an overall winner with score: 0{user_score}')
    elif user_score == computer_score:
        print(f"Your Final Score: 0{user_score}")
        print(f"Computer's Final Score: 0{computer_score}")
        print(f"Both share a equal score. It's a DRAW!")
    else:
        print(f"Your Final Score: 0{user_score}")
        print(f"Computer's Final Score: 0{computer_score}")
        print(f'Opponent wins with score: 0{computer_score}')


game(mode)
 



Practice questions for Python

ques: 1] Read a number & check whether it is pos. or negative? 

Solution:

try:

    num= int(input("Enter a number:"))

    if(num>0):

        print("number is positive")

    else:

        print("number is negative")


except:

    print("Please enter a number only. Thank You!")


Output: Enter a number:-1

number is negative


ques: 2] Read a number check whether it is odd or even?

Solution:

try:

    num= int(input("Enter a number:"))

    if(num%2==0):

        print("number is even")

    else:

        print("number is odd")


except:

    print("Please enter a number only. Thank You!")

Output:

python odd_even.py

Enter a number:100

number is even

ques: 3] Read the age of a person & display whether that person can vote or can not vote.

Solution:

try:

    Age= int(input("Enter your age:"))

    if(Age>=18):

        print("You're eligible to vote in elections!")

    elif(Age<=0):

        print("Please enter the correct age. Thank You!")

    else:

        print("You are under 18. You cannot Vote. Better Luck next time!")


except:

    print("Please enter a number only. Thank You!")

Output:

python castavote.py

Enter your age:-25

Please enter the coorect age. Thank You!

Ques 4] Read two numbers & display largest number

Solution:

try:

    num1,num2 = map(int, input().split())

    #map allocates the numbers at the correct position. Note that we don’t have to explicitly specify split(‘ ‘)

    # because split() uses any whitespace characters as a delimiter as default.

    if (num1<num2):

        print(num2,'is the largest')

    else:

        print(num1,'is the largest')

except:

    print("Please enter the correct values!")


Output: python largestnum.py
3 5555
5555 is the largest

Learning Python : Day 03

 











Phase 1:


#Step 1

word_list = ["aardvark", "baboon", "camel"]

chosen_word=random.choice(word_list)
print(chosen_word)

guess=input("Guess the Letter:").lower()

j=0
for i in chosen_word:
if i == guess:
j+=1
print(f'right: {j}')
else:
print('wrong')


Phase 2: Replace the underscores/blanks with the matched letter

display=[]

for i in chosen_word:
display+='_'
guess = input("Guess a letter: ").lower()
j=0
for letter in chosen_word:
if letter == guess:
display[j]=letter
j+=1
else:
j+=1
print(display)

Second Solution:

word_length=len(chosen_word)
display=[]
for _ in range(word_length):
display+="_"

for pos in range(word_length):
letter=chosen_word[pos]
if letter==guess:
display[pos]=letter

print(display)


Output:


Pssst, the solution is aardvark.
Guess a letter: a
['a', 'a', '_', '_', '_', 'a', '_', '_']

Phase 3: Guess until all the _ of the display are replaced by the chosen word and end the game

end_of_game=False
while(end_of_game!=True):
guess = input("Guess a letter: ").lower()

#Check guessed letter
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
print(display)
if '_' not in display:
end_of_game=True
print('You win')

Output:

Pssst, the solution is baboon.
Guess a letter: b
['b', '_', 'b', '_', '_', '_']
Guess a letter: a
['b', 'a', 'b', '_', '_', '_']
Guess a letter: b
['b', 'a', 'b', '_', '_', '_']
Guess a letter: o
['b', 'a', 'b', 'o', 'o', '_']
Guess a letter: n
['b', 'a', 'b', 'o', 'o', 'n']
You win

Day 04: Python Learning with Angela Yu

 Hey! Here, am on Day 02 of Angela's course. Though my heading says Day 04 which is actually done to stay in order of all the python learning blog posts to date.

Starting WILT blog with checked Day 02 completion in the daily tracker poster. This kinda gives

self-satisfaction.

So, the end project of today's day was to build a tip calculator. It splits the bill among "n" people on the basis of percentage tip. After all the calculations, it was showing the final amount to pay by "n" people.

Before coming to this project completed 3 exercises: BMI calculator, Your Life in Weeks, and adding a string as 2 digits number. Here, is the end result of the percentage tip calculator project:


Now, comes the What I learned in  DAY:02

1. len() function is incompetent in working with integers. If we even     try; the python compiler will throw an error: print(len(123456)) #It throws the traceback error: Traceback (most recent call last): File "main.py", line 1, in <module> print(len(123456)) TypeError: object of type 'int' has no len() Because we are trying to know the int's (integer) length & len function isn't trained to do so. It can only do the assigned task for strings only. 2. We have data types in python that allows using a different type of entries. a. String Syntax: a="1234" Subscript: The method of pulling out the particular character in the string type data is called a                    subscript. Syntax: print("helloworld"[0]) -> This will print out the H since H is the very first element placed at index 0. Note: 1. print("helloworld"[-1]) -> prints the last character. Initial index starts from zero                                             & last index starts from -1 2. print("123""345") -> concatenates the two strings b. Integer Syntax: a=1234 Note: 1. All the no.s whether positive or negative or whole no. comes under integer data types. 2. print(1234+1234) -> It will give the sum of two numbers. 3. print(123_456_758) -> Computer visulaises it as large no. & prints it after removing underscore:                                           123456758 c. Float Decimal numbers are floating-point numbers. Syntax: a=12.34 d. Boolean -Most Used- Syntax: a= True                 or                a=False Note: 1. While assignments, booleans don't have quotation marks around them.
    Otherwise, it would turn them into a String. 
❌ a="TRUE" ❌ a=true 3. Type checking in python is done by the keyword type(). It basically shows the data type/class type. Syntax: type(12) output: class<int> Example: print(type(len(input("What is your name\n")))) output: What is your namekawal <class 'int'> because we have printed out the length of the string 4. Type Conversion is actually a change. Using this we can implicitly or explicitly change the data type. Syntax: str(a) int(a) float(a) Example: a=100 print(a) print(type(a)) #type of the variable is integer s=str(a) #type casted the int vaiable to string print(s) print(type(s)) 5. Total we have 6 Mathematical Operators in Python which follow the PEMDAS order. The      calculation proceeds from left to right to have the final result. 1. + ( Addition ) 2. - ( Subtraction ) 3. ** ( Exponentiation ) 4. // ( Floor division ) : It chops off the result & gives an int as a final answer. 5. * ( Multiplication ) 6. / ( Division ) : It always gives the float as a final result. PEMDAS is: Paranthesis <- Exponentiation <- Multiplication <- Division <- Addition <- Subtraction     1                        2                            3                        4                    5                6
Example:
(3*3+3/3-3)
First: 3*3: 9
Second: 3/3: 1 9+1-3
Third: 9+1:10
Fourth: 10-3: 7 is the answer.

6.
Number manipulation in python is when we forcibly(using an inbuilt function) changes the               output's behavior.

For example:


print(8/3) -> It will output floating-point number.

In order to print the int type of the result, we need to convert it to type int

print(int(8/3)) -> It will output int type number.

 Another way of getting the non-floating point number is using the floor division.

print(8//3) -> It will chop off the after decimals & will print int type.

 If you check its type, will show the result is of type int.

print(type(8//3))
class <int>

One more most used manipulation is a round function which rounds off the number.

Example:

 print(round(8/3)) -> It will output instead of printing 2.666666 will print out 3.

Using this function, we can also go a step further & decide the number of desired precision.
Suppose, if you want to round it to 4 We can write it as:

 print(round(8/3,4)) -> It will output 2.6667

 OR

 bill_per_person=99/4
 bill="{:.4f}".format(bill_per_person)

 OR

 bill_per_person=99/4
 print(f"Bill per person is: {bill_per_person:.4f}")

 Note: F-strings in python are used when we are in need of printing different types of data types                       altogether.

s=5.7
t=True

Syntax:
print(f" {s},{t}")

Example:


score=0-> int
height=1.8 ->float
is_Winning=True ->boolean
print("your score is" + str(score) + str(height) + str(is_Winning )
                🡇
 In place of this, we will be using a different manipulation which is the f-string.
                🡇
print(f"your score is {score}") ->It does all the conversions in the backend. You don't have to worry about this.

print(f"your score is {score}, your height is {height}, your is_winning ia {is_winning}") -> handling conversions of multiple data types

Output:
Your score is 0, your height is 1.8, your is_winning is True

It cuts down the manual labor of type conversions.  

7.
Python has different ways of writing mathematical calculations. Among them, I loved  s+=1 the most. It basically adds 1 to the value of the s and stores the end result back to s.

The second way of writing mathematical calculations:
 s=4+2 -> output: 2

That was all! Overall, it was an amazing day while learning all the above-mentioned 7 pointers. The course is really well structured and has a notch to keep working on it.

Thank You and will see you again in my next day update. I am planning to do it today itself.

Let's see!