Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Unit 3 Indexing Slicing and Data Structure

indexing slicing

Uploaded by

upendra maurya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Unit 3 Indexing Slicing and Data Structure

indexing slicing

Uploaded by

upendra maurya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Indexing and Slicing

How to access characters of a array?


We can access characters of an array by using the following ways.
1. By using index
2. By using slice operator

1. By using index:
Python supports both +ve and -ve index.

+ve index means left to right(Forward direction)

-ve index means right to left(Backward direction)

In [2]: s="Upendra"
print(s[0])
print(s[3])
print(s[6])
print(s[-3])
print(s[-1])

U
n
a
d
a

In [3]: s="Upendra"
print(s[15]) # out of range because string is not that long

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[3], line 2
1 s="Upendra"
----> 2 print(s[15])

IndexError: string index out of range

Q 1. Write a program to accept some string from the keyboard and


display its characters by index wise(both positive and negative index)
In [7]: s=input("Enter Some String:")
i=0
for x in s:
print(f"The character present at positive index {i} is {x}")
i=i+1

Enter Some String:Jayesh


The character present at positive index 0 is J
The character present at positive index 1 is a
The character present at positive index 2 is y
The character present at positive index 3 is e
The character present at positive index 4 is s
The character present at positive index 5 is h

2. Accessing characters by using slice operator:


string slice means a part of the string (i.e, Sub string).

Syntax:
string_Name [beginindex:endindex:step]

Here,
beginindex: From where we have to consider slice(substring)
endindex: We have to terminate the slice(substring) at endindex-1
step: incremented / decremented value ### Note :
Slicing operator returns the sub string form beginindex to endindex - 1 ### Note:
If we are not specifying begin index then it will consider from beginning of the string.
If we are not specifying end index then it will consider up to end of the string.
The default value for step is 1

In [9]: s = 'abcdefghijk'
print(s[2:7])

cdefg

In [8]: s = 'abcdefghijk'
print(s[:7])

abcdefg

In [10]: s = 'abcdefghijk'
print(s[2:])

cdefghijk

In [11]: s = 'abcdefghijk'
print(s[:])

abcdefghijk

In [12]: s = 'abcdefghijk'
print(s[2:7:1])

cdefg

In [13]: s = 'abcdefghijk'
print(s[2:7:2])

ceg

In [14]: s = 'abcdefghijk'
print(s[2:7:3])

cf

In [15]: s = 'abcdefghijk'
print(s[::1])

abcdefghijk

s = 'abcdefghijk'
In [16]: print(s[::2])
acegik

In [17]: s = 'abcdefghijk'
print(s[::3])

adgj

In [18]: s="Learning Python is very very easy!!!"


s[1:7:1]

'earnin'
Out[18]:

In [19]: s="Learning Python is very very easy!!!"


s[1:7]

'earnin'
Out[19]:

In [20]: s="Learning Python is very very easy!!!"


s[1:7:2]

'eri'
Out[20]:

In [21]: s="Learning Python is very very easy!!!"


s[:7]

'Learnin'
Out[21]:

In [22]: s="Learning Python is very very easy!!!"


s[::]

'Learning Python is very very easy!!!'


Out[22]:

In [23]: s="Learning Python is very very easy!!!"


s[:]

'Learning Python is very very easy!!!'


Out[23]:

In [24]: s="Learning Python is very very easy!!!"


s[::-1]

'!!!ysae yrev yrev si nohtyP gninraeL'


Out[24]:

Q. Write a Python program to access each character of string


in forward and backward direction by using while loop.
In [2]: s="Learning Python is very easy !!!"
n=len(s)
i=0
print("Forward direction")
print()
while i<n:
print(s[i],end=' ')
i +=1
print('')
print('')
print("Backward direction")
print()
i=-1
while i>=-n:
print(s[i],end=' ')
i=i-1

Forward direction

L e a r n i n g P y t h o n i s v e r y e a s y ! ! !

Backward direction

! ! ! y s a e y r e v s i n o h t y P g n i n r a e L

Replacing a string with another string:


We can repalce a string with another string in python using a library
function replace().

Syntax:
s.replace(oldstring,newstring)

Here, inside 's', every occurrence of oldstring will be replaced with newstring.

In [4]: s="Learning Python is very difficult"


print(s)
s1=s.replace("difficult","easy")
print(s1)

Learning Python is very difficult


Learning Python is very easy

Splitting of Strings:
We can split the given string according to specified seperator by using
split() method.

We can split the given string according to specified seperator in reverse


direction by using rsplit() method.
Syntax :

l=s.split(seperator, Maximum splits)

Here, Both parameters are optional


The default seperator is space.
Maximum split defines maximum number of splits
The return type of split() method is List.
rsplit() breaks the string at the seperator staring from the right and returns a list of strings

In [5]: s="vijay dinanath chauhan"


l=s.split()
for x in l:
print(x)

vijay
dinanath
chauhan

In [6]: s="22-02-2018"
l=s.split('-')
for x in l:
print(x)

22
02
2018

In [7]: s="22-02-2018"
l=s.split() # no space in the string , so output is same as the given string
for x in l:
print(x)

22-02-2018

Write a program to print characters at odd position and


even position for the given String?
In [8]: s=input("Enter Some String:")
print("Characters at Even Position:",s[0::2])
print("Characters at Odd Position:",s[1::2])

Enter Some String:i love python


Characters at Even Position: ilv yhn
Characters at Odd Position: oepto

Program to merge characters of 2 strings into a single string


by taking characters alternatively.
In [10]: s1=input("Enter First String:")
s2=input("Enter Second String:")
output=''
i,j=0,0
while i<len(s1) or j<len(s2):
if i<len(s1):
output=output+s1[i]
i+=1
if j<len(s2):
output=output+s2[j]
j+=1
print(output)

Enter First String:upendra


Enter Second String:jayesh
ujpaeynedsrha

Write a program to remove duplicate characters from the


given input string.
Input: ABCDABBCDABBBCCCDDEEEF
Output: ABCDEF

In [13]: s=input("Enter Some String:")


l=[]
for x in s:
if x not in l:
l.append(x)
output=''.join(l)
print(output)

Enter Some String:ABCDABBCDABBBCCCDDEEEF


ABCDEF

Write a program to find the number of occurrences of each


character present in the given String.
Input: ABCABCABBCDE
Output: A-3,B-4,C-3,D-1,E-1

In [15]: s=input("Enter the Some String:")


d={}
for x in s:
if x in d.keys():
d[x]=d[x]+1
else:
d[x]=1
for k,v in d.items():
print("{} = {} Times".format(k,v))

Enter the Some String:ABCABCABBCDE


A = 3 Times
B = 4 Times
C = 3 Times
D = 1 Times
E = 1 Times

In [1]: a = ("a", "b", "c", "d", "e", "f", "g", "h")


print(a[4])

Data Structure
A data structure is a group of data elements that are put together under
one name. Data structure defines a particular way of storing and
organizing data in a computer so that it can be used efficiently.

We have already seen different types of data storage in previous units


such as (List,Tuple, Sets, and Dictionaries). Lets see some applications of
these data structures.

We have already explored LIST extensively, lets see remaining data


structures.

Q. Write a program to take a tuple of numbers


from the keyboard and print its sum and average
In [ ]:

In [2]: t=eval(input("Enter Tuple of Numbers:"))


print(type(t))
l=len(t)
sum=0
for x in t:
sum = sum + x
print("The Sum=",sum)
print("The Average=",sum/l)

Enter Tuple of Numbers:1,8,9,65,45,25,32


<class 'tuple'>
The Sum= 185
The Average= 26.428571428571427

Q Write a program to eliminate duplicates present in the list.


In [3]: l=eval(input("Enter List of values: "))
s=set(l)
print(s)

Enter List of values: 45,85,75,85,96,65,45,35,25


{96, 65, 35, 75, 45, 85, 25}

Q. Write a program to print different vowels present in the


given word
In [5]: w=input("Enter word to search for vowels: ")
s=set(w)
v={'a','e','i','o','u'}
d=s.intersection(v)
# The intersection() method returns a set that contains the similarity between two or mo
print("The different vowel present in",w,"are",d)
print('The number of different vowels : ',len(d))

Enter word to search for vowels: i love python


The different vowel present in i love python are {'e', 'i', 'o'}
The number of different vowels : 3

Q. Write a program to accept student name and marks from


the keyboard and creates a dictionary. Also display student
marks by taking student name as input.
In [6]: n=int(input("Enter the number of students: "))
d={}
for i in range(n):
name=input("Enter Student Name: ")
marks=input("Enter Student Marks: ")
d[name]=marks # assigninng values to the keys of the dictionary 'd'
while True:
name=input("Enter Student Name to get Marks: ")
marks=d.get(name,-1)
if marks== -1:
print("Student Not Found")
else:
print("The Marks of",name,"are",marks)
option=input("Do you want to find another student marks[Yes|No]")
if option=="No":
break
print("Thanks for using our application")

Enter the number of students: 3


Enter Student Name: upendra
Enter Student Marks: 85
Enter Student Name: jayesh
Enter Student Marks: 95
Enter Student Name: ramesh
Enter Student Marks: 45
Enter Student Name to get Marks: upendra
The Marks of upendra are 85
Do you want to find another student marks[Yes|No]No
Thanks for using our application

Differences between List and Tuple:


List and Tuple are exactly same except small difference: List objects are mutable where as Tuple objects
are immutable.
In both cases insertion order is preserved, duplicate objects are allowed, heterogenous objects are
allowed, index and slicing are supported.

In [ ]:

List Comprehensions
It is very easy and compact way of creating list objects from any iterable objects(like
list,tuple,dictionary,range etc) based on some condition.
Syntax:
list=[expression for item in list if condition]

Consider an example, If you want to store squares of numbers form 1 to 10 in a list,

In [9]: l1=[]
for x in range(1,11):
l1.append(x*x)
print(l1)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In the above case, the program consisting 4 lines of code. Now for the same purpose
we will write the following code in more concised way.

In [10]: l1 = [x*x for x in range(1,11)]

print(l1)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Few more examples of list comprehension


In [11]: l =[2**x for x in range(1,11)]
print(l)

[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]

In [12]: l = [x for x in range(1,11) if x%2==0]


print(l)

[2, 4, 6, 8, 10]

In [13]: l = [x for x in range(1,11) if x%2==1]


print(l)

[1, 3, 5, 7, 9]

In [14]: l = [x**2 for x in range(1,11) if (x**2)%2==1]


print(l)

[1, 9, 25, 49, 81]

In [15]: words=["Upendra","Jayesh","Rahul","Ajay","Puja"]
l=[w[0] for w in words]
print(l)

['U', 'J', 'R', 'A', 'P']

In [16]: words=["Upendra","Jayesh","Rahul","Ajay","Puja"]
l=[w for w in words if len(w)>5]
print(l)

['Upendra', 'Jayesh']

In [17]: num1=[10,20,30,40]
num2=[30,40,50,60]
num3=[ i for i in num1 if i not in num2]
print(num3)

[10, 20]

In [18]: words="the quick brown fox jumps over the lazy dog".split()
print(words)
l=[[w.upper(),len(w)] for w in words]
print(l)

['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']


[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE',
3], ['LAZY', 4], ['DOG', 3]]

Set Comprehension
Syntax:
s = {expression for x in sequence condition}

In [7]: s = {x*x for x in range(6)}


print(s)

{0, 1, 4, 9, 16, 25}

In [8]: s={2**x for x in range(2,10,2)}


print(s)

{16, 256, 64, 4}

In [ ]:

A sample problem for solving friction on inclined


plane problem

solving friction on inclined plane

Fn=mass*g*cos(0) # angle in radian


Ff=Fn*cof # cof means coefficint of friction
acc=(m*g*sin(0)-Ff)/m

If the object is not sliding (weight_parallel ≤ friction_force_max) the acceleration is zero.

In [1]: import numpy as np

def solve_friction_inclined_plane(mass, angle, friction_coefficient):


"""
Solve an inclined plane problem with friction.

Parameters:
- mass: Mass of the object (kg).
- angle: Inclination angle of the plane (degrees).
- friction_coefficient: Coefficient of friction between the object and the plane.

Returns:
- normal_force: Normal force exerted by the plane on the object (N).
- friction_force: Friction force opposing motion (N).
- acceleration: Acceleration of the object along the incline (m/s^2).
"""

# Constants
g = 9.8 # Acceleration due to gravity (m/s^2)

# Convert angle to radians


angle_rad = np.radians(angle)

# Decompose forces into components


weight_parallel = mass * g * np.sin(angle_rad)
weight_perpendicular = mass * g * np.cos(angle_rad)

# Determine normal force


normal_force = weight_perpendicular

# Determine friction force using the coefficient of friction


friction_force_max = friction_coefficient * normal_force

# Check if the friction force is enough to prevent sliding


if weight_parallel <= friction_force_max:
# Object is not sliding; friction force is equal to weight_parallel
friction_force = weight_parallel
acceleration = 0.0
else:
# Object is sliding; friction force is at its maximum value
friction_force = friction_force_max

# Calculate acceleration using Newton's second law


acceleration = (weight_parallel - friction_force) / mass

return normal_force, friction_force, acceleration

# Example usage:
mass = 5.0 # kg
angle_of_inclination = 30.0 # degrees
friction_coefficient = 0.3

normal_force, friction_force, acceleration = solve_friction_inclined_plane(mass, angle_o

print(f"Normal Force: {normal_force} N")


print(f"Friction Force: {friction_force} N")
print(f"Acceleration: {acceleration} m/s^2")

Normal Force: 42.4352447854375 N


Friction Force: 12.730573435631248 N
Acceleration: 2.3538853128737496 m/s^2

In [ ]:

In [ ]:

Assignement Questions
please use assignment submission template to submit
assignment

Please include code approach for all questions.

1. Write a program that defines a list of countries that are a member of BRICS, Check whether a country is
a member of BRICS or not.
2. Write a program that has a list of numbers (both positive as well as negative). make a new tuple that
has only positive values from this list.
3. Write a program that accepts different number of arguments and return sum of only the positive values
passed to it.
4. Write a program that creates two sets-squares and cubes in range 1-10. Demonstrate the sue of
update(),pop(),remove(),and clear() functions.
5. Write a program that creates a dictonary of radius of circle and its circumference.
6. Write a unique program considering the concepts learnt upto this unit.

In [ ]:

You might also like