0% found this document useful (0 votes)
35 views9 pages

Slicing

Uploaded by

amit.cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views9 pages

Slicing

Uploaded by

amit.cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Slicing

Syntax of String Slicing in Python


substring = s[start : end : step]
Parameters:
 s: The original string.
 start (optional): Starting index (inclusive). Defaults to 0 if
omitted.
 end (optional): Stopping index (exclusive). Defaults to the end
of the string if omitted.
 step (optional): Interval between indices. A positive value
slices from left to right, while a negative value slices from right
to left. If omitted, it defaults to 1 (no skipping of characters).
Return Type: The result of a slicing operation is always a string
(str type) that contains a subset of the characters from the original
string.
Using Negative Indexing in Slicing
Negative indexing is useful for accessing elements from the end
of the String. The last element has an index of -1, the second last
element -2 and so on.
s="welcome how are you"
print(s[0:5])
s = "abcdefghijklmno"

print(s[-4:])

print(s[:-3])

print(s[-5:-2])

print(s[-8:-1:2])

welco
lmno
abcdefghijkl
klm
hjln

Reverse a String Using Slicing


s = "Python"

# Reverse the string


print(s[::-1])
Retrieve All Characters
s = "Hello, World!"

# Get the entire string


s2 = s[:]
s3 = s[::]

print(s2)
print(s3)
Hello, World!
Hello, World!

Get All Characters Before or After a Specific Position


s = "Hello, World!"

# Characters from index 7 to the end


print(s[7:])

# Characters from the start up to index 5 (exclusive)


print(s[:5])
World!
Hello

Extract Characters Between Two Positions


s = "Hello, World!"

# Characters from index 1 to index 5 (excluding 5)


print(s[1:5])
ello

Get Characters at Specific Intervals


s = "abcdefghi"

# Every second character


print(s[::2])

# Every third character from index 1 to 8 (exclusive)


print(s[1:8:3])
acegi
beh

Slicing lists
# Extract elements from a list
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
# Output: [20, 30, 40]

# Skip elements using steps


print(numbers[::2])
# Output: [10, 30, 50]
[20, 30, 40]
[10, 30, 50]

Numpy

1-D Arrays
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))
[1 2 3 4 5]
<class 'numpy.ndarray'>

2-D Arrays
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)
[[1 2 3]
[4 5 6]]

3-D arrays
import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(arr)

Slicing in NumPy
[[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]]

Check Number of Dimensions


import numpy as np

a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

Access Array Elements


import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[0])

Access 2-D Arrays


import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 1st row: ', arr[0, 1])


2nd element on 1st dim: 2

Access the element on the 2nd row, 5th column:


import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])


print('5th element on 2nd row: ', arr[1, 4])

Access 3-D Arrays


Access the third element of the second array of the first
array:
import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(arr[0, 1, 2])

Example Explained
arr[0, 1, 2] prints the value 6.

And this is why:

The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]

The second number represents the second dimension, which also contains
two arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]

The third number represents the third dimension, which contains three
values:
4
5
6
Since we selected 2, we end up with the third value:
6
Slicing 1D arrays

import numpy as np

# Create a 1D array
array = np.array([10, 20, 30, 40, 50])

# Slice elements from index 1 to 3


print(array[1:4])
# Output: [20 30 40]

# Apply step
print(array[::2])
# Output: [10 30 50]
[20 30 40]
[10 30 50]

Slicing multi-dimensional arrays

# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Slice the first two rows and first two columns


print(array_2d[:2, :3])
[[1 2 3]
[4 5 6]]

Slicing in pandas
import pandas as pd

# Create a sample DataFrame


student_data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Score': [85, 90, 95]}

students = pd.DataFrame(student_data)

# Slice the first two rows


print(students[:2])
# Output:
# Name Age Score
# 0 Alice 25 85
# 1 Bob 30 90
1. Given an array of strings arr[], the task is to return
the longest common prefix among each and every strings
present in the array. If there’s no prefix common in all the
strings, return “”.
Examples:
Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]
Output: “gee”
Explanation: “gee” is the longest common prefix in all the
given strings: “geeksforgeeks”, “geeks”, “geeks” and
“geezer”.
Input: arr[] = [“apple”, “ape”, “april”]
Output : “ap”
Explanation: “ap” is the longest common prefix in all the given
strings: “apple”, “ape” and “april”.
Input: arr[] = [“hello”, “world”]
Output: “”
Explanation: There’s no common prefix in the given strings.
Approach:
The idea is to sort the array of strings and find the common prefix
of the first and last string of the sorted array. Sorting is used in
this approach because it makes it easier to find the longest
common prefix. When we sort the strings, the first and last strings
in the sorted list will be the most different from each other in terms
of their characters. So, the longest common prefix for all the
strings must be a prefix of both the first and the last strings in the
sorted list.
Illustration:
 Given array of strings is [“geeksforgeeks”, “geeks”, “geek”, “geezer”].
 After sorting it becomes [“geek” ,”geeks” ,”geeksforgeeks” ,”geezer”].
 Now, to find the longest common prefix, we only need to compare
the first and last strings (“geek” and “geezer“) because any common prefix
between these two will also be a prefix for all the strings in between.
 In this case, the common prefix between “geek” and “geezer” is “gee“, which is
the longest common prefix for all the strings.

Sol 1:

str = ["flower", "flow", "floight"]

str.sort()
print(str)

first=str[0]#first

print(first)

last=str[-1]#last

print(last)

print(len(first))

print(len(last))

print(first[0])

print(last[0])

i=0

while i < len(first) and i < len(last) and first[i] == last[i]:

i += 1

print(i)

print(first[:i])

def longest_common_prefix(strs):
if not strs:
return ""

# Sort the array to bring the smallest and largest strings


(lexicographically) to the ends
strs.sort()

# Compare the first and last strings only (sufficient after sorting)
first = strs[0]
last = strs[-1]
i = 0

while i < len(first) and i < len(last) and first[i] == last[i]:


i += 1

return first[:i]

# Example usage:
words = ["flower", "flow", "floight"]
print("Longest Common Prefix:", longest_common_prefix(words))
2.Given a string s consisting of lowercase English Letters. Return the first non-repeating
character in s.
If there is no non-repeating character, return '$'.
def first_non_repeating_char(s):
from collections import Counter

# Count frequency of each character


freq = Counter(s)

# Find first character with frequency 1


for char in s:
if freq[char] == 1:
return char

return '$'

# Example usage:
s = "aabbcddeffg"
print("First non-repeating character:", first_non_repeating_char(s)) #
Output: 'c'
2. You are given two strings of equal lengths, s1 and s2. The task is to check if s2 is a
rotated version of the string s1.

If s2 is a rotation of s1, then it will always be a substring of s1 + s1.

For example:

s1 = "abcd"

s2 = "cdab" → s1 + s1 = "abcdabcd" → "cdab" is in "abcdabcd"

def is_rotated(s1, s2):


if len(s1) != len(s2):
return False
return s2 in (s1 + s1)

# Example usage:
s1 = "abcd"
s2 = "cdab"
print("Is rotated:", is_rotated(s1, s2)) # Output: True

You might also like