Problem Solving using Python - CodeTantra Solutions | Level 1 to Level 17

CoderIndeed
14 minute read
0

Download Study Material

Level 1

Language Features

# Q1 ✅ The sequence of instructions (in the form of source code) written in a computer programming language is called a computer program.
# Q2 ✅ The Python programming language evolved through many versions.
# Q3 ✅ Python source code is written and saved in a file with .py extension.
# Q4
print("Python is Easy")

# Q5
print("Python is not Typhoon")

# Q6
print("Abracadabra"*7)

# Q7
print("where", "the" "re", "is", "a", "will,", "there", "is", "a", "way")

# Q8 ✅ Python is an interpreted language.
✅ A Python program can execute C and C++ programs also.
✅ A Python program written on Windows operating system will also execute on Linux operating system as it is portable.
Level 2

Comments

# Q1
# This is my first program
print("I am a Python Guru")
# print("Python is not cool")
# print() is used to print the message on console
    

# Q2
print("1")
# print("2")
print("3")
# print("4")
print("5")
# print("6")
print("7")
# print("8")
print("9")
# print("10")
print("11")
# print("12")
  print("13")

# Q3
  def add(a, b):
    """Return sum of given arguments."""
    return a + b
def power(b, e):
    """Return the power value.
    
    b -- is the base
    e -- is the exponent
    """
    return b ** e
print(add.__doc__)
    
  print(power.__doc__)

Identifiers and Keywords

# Q1 ✅ Identifiers are used for identifying entities in a program.
✅ string_1 is valid identifier.
✅ Identifiers can be of any length.
# Q2 ✅ Python version 3.5 has 33 keywords.
✅ The keyword nonlocal does not exist in Python 2.
✅ Interpreter raises an error when you try to use keyword as a name of an entity.
# Q3
import keyword
print('and is a keyword :', keyword.iskeyword('and'))
#Fill in the missing code in the below lines
print('exec is a keyword :', keyword.iskeyword('exec'))
print('nonlocal is a keyword :', keyword.iskeyword('nonlocal'))
print('False is a keyword :',keyword.iskeyword('False') )
  
Level 3

Variable and Assignment

# Q1
snake= "King Cobra"
length=18
  print(snake, "can grow up to a length of", length, "feet")

# Q2
value1 = value2 = value3 = "Hello"
print(value1)
print(value2)
print(value3)
# Assign values to variables and print again
value1=99
value2="Hello Python"
value3="Hello World"
print(value1)
print(value2)
print(value3)
  

# Q3
kilometers = int(input("Enter a value: ")) # assign the correct value
convertfactor = 0.621371 # assign the correct value
miles =  (kilometers) * (convertfactor)# multiply kilometers and convertfactor
print("Miles:",miles)
  

# Q4
q=999
w=24.789
e="Python Interpreter"
print(q)
print(w)
print(e)
  

# Q5
str = input("Enter a value: ")
a=b=c= str
print("Value of a:",a)
print("Value of b:",b)
print("Value of c:",c)
  
Level 4

Indentation

# Q1
if 100.0 > 10.0:
    print("Small Value:", 10.0)
else:
    print("Large Value:", 100.0)
  

# Q2
print("Hello Python")
  

Understanding Expressions

# Q1
if 100.0 > 10.0:
    print("Small Value:", 10.0)
else:
    print("Large Value:", 100.0)
  

# Q2
print("Hello Python")
  

Level 5

Different Data Types

# Q1 ✅ In Python, we need not specify the data type of the variable.
✅ type() function in Python is used to know which datatype of value the variable holds.

Numbers

# Q1
a = 365
print (type(a))

a = 345.65
print (type(a))

a = 45 + 5j
print(type(a))
  

Strings

# Q1 ✅ Encoding means converting strings of characters into numbers.
Level 6

Lists

# Q1
list1 = [1.0, 2.3, "hello"]
list2 = ["hi", 8.3, 9.6, "how"]
print("List1 Elements are:", list1); print("List2 Elements are:",list2)
print("List after Concatenation:",list1+list2)

# Q2
list1 = ["hi", "hello", "Lists"]
print(list1[0]);print(list1[1]);print(list1[2])
list1[2] = "Python"
print(list1)
list1.append('Code is Life')
print(list1)
list1.extend([45, 67, 89])
print(list1)
  

Sets

# Q1 ✅ A set is represented using curly braces { } .

Tuples

# Q1 ✅ tuples are immutable.
✅ Converting a tuple into a list and list into tuple is possible.
# Q2
mytuple = ("this", 10.0, "is", "float", 3.6)

# Print value at index 0
print(mytuple[0])
# Print value at index 1
print(mytuple[1])
# Print value at index -1
print(mytuple[-1])
# Print all the values from index 0
print(mytuple)
# Print all the values except the last value
mytuple=mytuple[:-1]
print(mytuple)
mytuple=(3.6,"float","is",10.0,"this")
print(mytuple)
  

# Q3
mytuple = ("i", "love", "python")
print("Given Tuple:",mytuple)
list1=list(mytuple)
print("After Converting Tuple into List:",list1)
list1[1]="practice"
print("List after changing element:",list1)
mytuple=tuple(list1)
print("After Converting List into Tuple:",mytuple)
  
Level 7

Dictionaries

# Q1 ✅ Dictionary is a Python data type to store multiple values.
✅ Keys of the dictionary cannot be changed.
# Q2
mydict = {"name":"Rama", "branch":"CSE", "place":"HYD"}
print(mydict["name"])
print(mydict["branch"])
print(mydict["place"])
  

# Q3
  mydict = {"game":"chess","dish":"chicken","place":"home"}
print(mydict.get("game"))
print(mydict.get('dish'))
print(mydict.get("place"))
mydict["game"] = "cricket" # change game chess to cricket using respective key
print(mydict['game'])
  

Data Type Conversions

# Q1
a = int(input("Enter a value: "))
b = int(input("Enter b value: "))
# print a value respective string
print(str(a))
# print a value respective char
print(chr(a))
# print a value respective hexadecimal value
print(hex(a))
# print a and b of complex number
print(complex(a,b))
  

# Q2
list1 = ["key1","key2","key3"]
list2 = ["value1","value2","value3"]
print(list1)
print(list2)
mydict = zip(list1,list2)	# using zip() function we can create dictionary with two lists(one list for keys and one list for values)
set1=set(mydict)
# convert dictionary into set using set() method
# print elements in  sorted order
print(sorted(set1))
Level 8

Input and Output Statements

# Q1
place = input("Enter your favourite place: ")

# Print your favourite place
print("My favourite place is:",place)
  
# Q2
lang = input("Enter Language: ")
print("My Favourite Language is",lang)
  

# Q3
name = "Pretty"
branch = "CSE"
score = "10"
print("Hello", name,"your branch is", branch,"and your score is", score)
  
# Q4
# Take an integer input from the user and store it in variable "a"
a=input("a: ")
# Take an integer input from the user and store it in variable "b"
b=input("b: ")
# print "a" value at 0 index and "b" value at 1 index
print("The value of a = {0}, b = {1} ".format(a,b))
# print by changing the index postions of "a" and "b" and observe the output
print("The value of a = {1}, b = {0} ".format(a,b))
  

# Q5
# take float number from the user
a=input("a: ")
# print up to 2 decimal points
print("{0:.2f}".format(int(a)))
# print up to 6 decimal points
print("{0:.6f}".format(int(a)))
# take int number from the user
b=input("Enter b value: ")
# print the number with one space
print("%d"%(int(b)))
# print the number with two spaces
print("%2d"%(int(b)))
# print the number with three spaces
print("%3d"%(int(b)))
# print the given number b in octal form
print("octal:",oct(int(b))[2:])
# print the given input b in hexadecimal form
print("hex:",hex(int(b)).upper()[2:])
  

Basics of Python Programming

# Q1 ✅ Python is used by most of the top companies.
✅ By using Python we can implement GUI.
✅ Python is a cross platform language.
# Q2 ✅ Compiler takes entire block of code as a single unit to check and identify the errors in program.
Level 9

Arithmetic Operators

# Q1 ✅ Python supports 7 arithmetic operators.
✅ An exponent operator is represented by ** in Python.
✅ // is called as Floor division operator.
# Q2
  #Arithmetic Operators are +, -, *, /, **, %, //
num1 = int(input("num1: "))
num2 = int(input("num2: "))
print("%d + %d = %d" % (num1,num2,num1+num2))
print("%d - %d = %d" % (num1,num2,num1-num2))
print("%d * %d = %d" % (num1,num2,num1*num2))
print("{} / {} =".format(num1,num2),num1/num2)
print("%d ** %d = %d" % (num1,num2,num1**num2 ))
print("{} % {} =".format(num1,num2),num1%num2)
print("%d // %d = %d" % (num1,num2,num1//num2))
    

# Q3
n1 = int(input ("num1: "))
n2 = int(input ("num2: "))
print("Addition of",n1,"and",n2,"=",n1+n2)
print("Subtraction of",n1,"and",n2,"=",n1-n2)
print("Multiplication of",n1,"and",n2,"=",n1*n2)
print("Division of",n1,"and",n2,"=",n1/n2)
  

# Q4
n1 = int(input("num1: "))
n2 = int(input("num2: "))
print("Exponent of",n1,"with",n2,"=",n1**n2)
print("Modulus of",n1,"and",n2,"=",n1%n2)
print("Floor Division of",n1,"and",n2,"=",n1//n2)
  

# Q5
n=int(input("num1: "))
m=int(input("num2: "))
print("Exponent of",n,"with",m,"=",n**m)
print("Modulus of",n,"and",m,"=",n%m)
print('Floor Division of',n,"and",m,"=",n//m)
  

# Q6
a=int(input("num1: "))
b=int(input("num2: "))
print(a,"//",b,"=",a//b)
print(a,"%",b,"=",a%b)
  

Comparison Operators

# Q1
n1 = int(input("num1: "))
n2 = int(input("num2: "))
print("Is",n1,"greater than",n2,"=",n1>n2)
print("Is",n1,"less than",n2,"=",n1<n2)
print("Is",n1,"equal to",n2,"=",n1==n2)
print("Is",n1,"not equal to",n2,"=",n1!=n2)
print("Is",n1,"less than or equal to",n2,"=",n1<=n2)
print("Is",n1,"greater than or equal to",n2,"=",n1>=n2)
  

# Q2
n1 = int(input ("num1: "))
n2 = int (input ("num2: "))
print("Is", n1, "greater than", n2, "=", n1>n2)
print("Is", n1, "less than", n2, "=", n1<n2)
print("Is", n1, "equal to", n2, "=", n1==n2)
print("Is", n1, "not equal to",n2,"=",n1!=n2)
print("Is", n1, "greater than or equal to",n2,"=", n1>=n2)
print("Is",n1,"less than or equal to",n2,"=",n1<=n2)

# Q3
m=input('str1: ')
n=input('str2: ')
print('Is',m,'greater than',n,"=",(m>n))
print('Is',m,'less than',n,"=",m<n)
print("Is",m,"equal to",n,"=",m==n)
print("Is",m,"not equal to",n,"=",(m)!=(n))
print("Is",m,"greater than or equal to",n,"=",m>=n)
print("Is",m,"less than or equal to",n,"=",m<=n)
                                                

# Q4
m=input('str1: ')
n=input('str2: ')
print('Is',m,'greater than',n,"=",(m>n))
print('Is',m,'less than',n,"=",m<n)
print("Is",m,"equal to",n,"=",m==n)
print("Is",m,"not equal to",n,"=",m!=n)
print("Is",m,"greater than or equal to",n,"=",m>=n)
print("Is",m,"less than or equal to",n,"=",m<=n)
  
Level 10

Assignment Operators

## Q1
```python
n=int(input("x: "))
m=int(input("y: "))
a=n
b=m
n+=m
print("x += y: x =",n,"and y =",m)
n,m=a,b
n-=m
print("x -= y: x =",n,"and y =",m)
n,m=a,b
n*=m
print("x *= y: x =",n, "and y =",m)
n,m=a,b
n=n/m
print("x /= y: x =",n, "and y =",m)
n,m=a,b
n=n**m
print("x **= y: x =",n, "and y =",m)
n,m=a,b
n=n//m
print("x //= y: x =",n, "and y =",m)
n,m=a,b
n=n%m
print("x %= y: x =",n, "and y =",m)
n=m
print("x = y: x =",n, "and y =",m)

## Q2
# Assignment Operators =, +=, -=, *=
n=int(input("x: "))
m=int(input("y: "))
a=n
b=m
n=m
print("x = y:",n)
n,m=a,b
n+=m
print("x += y:",n)
n,m=a,b
n-=m
print("x -= y:",n)
n,m=a,b
n*=m
print("x *= y:",n)

## Q3
# Assignment Operators  /= , %=, **=, //=
n = int(input("x: "))
m = int(input("y: "))
a=n
b=m
n/=m
print('x /= y:' , n)
n,m=a,b
n%=m
print ('x %= y:' , n)
n,m=a,b
n**=m
print ('x **= y:' , n)
n,m=a,b
n//=m
print ('x //= y:' , n)

Comparison Operators

## Q1 ✅ In (NOT) ~ Bits that are 0 become 1, and those that are 1 become 0. ## Q2
#Program to illustrate bit wise operators >>, <<
n=int(input("x: "))
m=int(input("y: "))
x=n>>m
print(n,">>",m,"is",x)
y=n<<m
print(n,"<<",m,"is",y)

## Q3
#Program to illustrate the bitwise operators &, |
x=int(input("x: "))
y=int(input("y: "))
print("{} & {}:".format(x,y),x&y)
print("{} | {}:".format(x,y),x|y)

## Q4 ✅ One's complement converts 0's into 1's and 1's into 0's.
✅ One's complement of the short int value 2 is 11111101.
## Q5
#Program to illustrate bitwise operators ~, ^
x=int(input("x: "))
y=int(input("y: "))
print("~ {}:".format(x),~x)
print("{} ^ {}:".format(x,y),x^y)

## Q6
  x=int(input("x: "))
y=int(input("y: "))
print("{} >> {} is".format(x,y),x>>y)
print("{} << {} is".format(x,y),x<<y)
print("{} & {} is".format(x,y),x&y)
print("{} | {} is".format(x,y),x|y)
print('~ {} is'.format(x),~x)
print("{} ^ {} is".format(x,y),x^y)

## Q7
x=int(input("num1: "))
y=int(input("num2: "))
c=((-y)+x)
print("difference:",c)

Level 11

Logical Operators

Q1 ✅ In logical and the result is true if the both operands are true.
Q2
x=input("M or F: ")
y=int(input("age: "))
if (x=="M") and y>=65:
    print("Eligible for Concession")
elif (x=="F") and y>=60:
    print("Eligible for Concession")
else:
    print("Not Eligible for Concession")

Q3
# write your code here
x=int(input("a: "))
y=int(input("b: "))
z=int(input("c: "))
if (x==y==6) and z!=6:
    print("True")
else:
    print("False")

Q4
# Program to illustrate logical and
a = int(input("a: "))
b = int(input("b: "))
if(a==6 or b==6 or a+b==6 or a-b==6):
    print("True")
else:
    print("False")

Q5
# Program to illustrate logical not
x=input("Enter day: ")
if not(x=="SAT" or x=="SUN"):
    print("Not Weekend")
else:
    print("Weekend")

Membership Operators

Q1 ✅ in and not in operators check the existence of a member in a collection.
✅ if in operator returns False, not in operator will return True.
✅ An empty string is part of every other string.
Q2
x=input("str1: ")
y=input("str2: ")
print(y,"in",x,":",y in x)

Q3
#Program to illustrate in and not in for strings
x=input("str1: ")
y=input("str2: ")
print(y,"in",x,"is:",y in x)
print(y,"not in",x,"is:",y not in x)

Q4
# Program to illustrate membership
L1 = ['A', '123', 'Ramana', [1, 2], 34.56, '55']
# for 34.56 returns False as output because input() return type is True so it converts 34.56 as string.

# write your code here
print(L1)
x=input("element: ")
print(x,"in",L1,"is:",x in L1)
print(x,"not in",L1,"is:",x not in L1)

Level 12

Identity Operators

Q1 ⦿ id(object) is unique and Constant for an object during its lifetime.
Q2
x=int(input("Enter an integer: "))
y=int(input("Enter the same integer: "))
print("x is y",x is y)
print("x is not y",x is not y)
a=float(input("Enter a Float Number: "))
b=float(input("Enter the same Number: "))
print("x is y",a is b)
print("x is not y",a is not b)

Q3
x=int(input("x: "))
y=int(input("y: "))
print("{} is {}".format(x,y),x is y)

Q4
x=int(input("x: "))
y=int(input("y: "))
print("{} is {}".format(x,y),x is not y)
Operators Precedence

Q1 ✅ Operator precedence is performed based on priority of an operator.
✅ Associativity is used when two operators of same precedence are in the same expression.
Q2 No Any Question.
Q3
a=int(input("a: "))
b=int(input("b: "))
print("{} + {} * 5 =".format(a,b),a+b*5)
print("{} + {} * 6 / 2 =".format(a,b),a+b*6/2)

Q4
a=int(input("a: "))
b=int(input("b: "))
print("{} + {} * 5 =".format(a,b),a+b*5)
print("{} + {} * 5 * 10 / 2 =".format(a,b),a+b*5*10/2)

Q5
a=int(input("a: "))
b=int(input("b: "))
c=int(input("c: "))
print("a and b or c".format(a,b,c),a and b or c)
print("a or b and c".format(a,b,c),a or b and c)

Q6
a=int(input("a: "))
b=int(input("b: "))
c=int(input("c: "))
print("{} and {} and {} or {} is".format(a,b,c,a),a and b and c or a)
print("{} or {} and {} and {} is".format(a,b,c,a),a or b and c and a)

Level 13

Practise Programs

Q1
x=int(input(("kg: ")))
lb=2.2*x
print("lb:",lb)

Q2
c=float(input("temp in celsius: "))
f=1.8*c+32
print("temp in fahrenheit is",f)

Q3
a=int(input("a: "))
b=int(input("b: "))
print("{} + {} =".format(a,b),a+b)
print("{} - {} =".format(a,b),a-b)
print("{} * {} =".format(a,b),a*b)
print("{} / {} =".format(a,b),a/b)
print("{} ** {} =".format(a,b),a**b)
print("{} % {} =".format(a,b),a%b)
print("{} // {} =".format(a,b),a//b)

Level 14

Introduction to Algorithms

Q1
✅ Problem solving is a systematic approach to define and solve a problem.
◻︎ The order to solve a problem is to first provide the solution followed by the problem definition.
✅ Few techniques are required to solve a particular problem which help in deriving a logic to solve the problem.
◻︎ Algorithms, Flowcharts, Pie Charts are some of the techniques of problem solving.
✅ Algorithms,Flowcharts, Pseudo Code and Programs are the techniques used to solve a problem.
Q2
◻︎ Algorithm means a mathematical formula.
✅ It is very easy to write the code in any programming language after developing an algorithm for that problem.
◻︎ Only one algorithm can be written for any problem.
✅ After a finite number of steps an algorithm must reach an end state.
Q3
◻︎ The more time an algorithm takes to execute, the better is the algorithm.
✅ The lesser memory a program takes to execute, better is the algorithm.
◻︎ Only one algorithm can be written for any problem and is the only preferred way.
◻︎ The quality of an algorithm is determined by the person who wrote it.
Q4
miles = int(input("miles: "))
if (miles > 0):
    print("kilometers:",miles*1.609)
    # convert the given miles into kilometers and print the result

else:
    print("not positive value")

Q5
t=input("temp with unit: ")
g=t[0:-1]
n=int(g)
x=t[-1:]
s=['c','C','f','F']
if x in s:
    if (x=='c')or (x=='C'):
        a=n*9/5+32
        y=round(a,2)
        print(n,"C =",y,"F")

    else:
        b=(5/9)*(n-32)
        z=round(b,2)
        print(n,"F =",z,"C")
else:
    print("unrecognized unit:",x)

Level 15

Building Blocks of Algorithms

Q1
◻︎ Selection, Sequence are the only building blocks of constructing an algorithm.
◻︎ A statement is a collection of instructions corresponding to multiple actions.
✅ Input to a computer, processing the input and showing the processed result as output are examples of a statement.
✅ Execution of individual statements in a given order is called control flow.
✅ In selection statement, the program control is transferred to a part of the program based on a condition.
✅ A function causes the control to be passed to block of code when referenced using its name.
Q2
num1 = int(input("num1: "))
num2 = int(input("num2: "))
sum = num1 + num2
print("sum of %d, %d = %d" %(num1, num2, sum))

Q3
n=int(input("age: "))
if n>=0:
    if n>17:
        print("eligible")
    else:
        print("not eligible")
else:
    print("age cannot be negative")

Q4
nvalues=int(input("n: "))
if(nvalues>0 and nvalues<51):
    for i in range(1, nvalues + 1):
        print(i,end=" ")
else:
    print("enter valid value")

Q5
n1=int(input('num1: '))
n2=int(input('num2: '))
def add2Num():
    # c=n1+n2
    print("The sum of {} and {} is".format(n1,n2),n1+n2)

add2Num() # caling the function add2Num

Level 16

Pseudo Code

Q1
◻︎ Programs written in pseudo code can be compiled and executed.
✅ Pseudo code has no standards but guidelines exist.
◻︎ You should know programming language to write pseudo code.
◻︎ Multi line iterations cannot be represented in pseudo code.
Q2
◻︎ In an if-else condition, the else part gets executed if the condition is true.
✅ In the For-loop the condition is evaluated for each iteration of the loop.
◻︎ The While loop is executed only when the condition is false.
✅ In the While loop, the condition is evaluated for each iteration of the loop.
Q3
n=int(input("num: "))
sum=0
s=n
if n>0:
    while n>0:
        sum=sum+n
        n=n-1
    print("sum:",sum)
else:
    print("enter positive value")

Q4
◻︎ The advantage of Pseudo code is that it is ambiguous and uncertain.
✅ Pseudo code can be translated to high level languages.
◻︎ Pseudo code by nature is structured and expressive.
✅ Pseudo code can easilly understand by the programmers and users.
Flow Charts
Q1
✅ Diamond shaped symbol is used in the flowcharts to indicate a decision (or branching).
✅ A flowchart is a pictorial representation of an algorithm.
✅ An algorithm and a flowchart can help us to clearly specify the sequence of steps to solve a given problem.
◻︎ A flowchart gives us a clear overview of the program but not the solution
Q2
# write your code here
r=float(input("Enter the radius : "))
if r>=0:
    a=3.14*r*r
    print("Area of circle = %f"%a)
else:
    print("Enter a positive value upto 100")

Q3
✅ Flow charts help in understanding the logic of a program.
✅ Flowcharts help in debugging process.
◻︎ Flowcharts may become complex and clumsy for simple problems.
✅ A lot of time is needed for drawing flow charts for large projects.
Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !