Longest and shortest word

Longest and shortest word

EasyString Programs · 7 of 106

Write a Python program to find the longest and the shortest word in a string.

Input
"Python makes string handling easy"
Output
Longest: handling
Shortest: easy

Approach

  1. Split into words and use max / min with key=len.

Solution

Python
text = "Python makes string handling easy"words = text.split()print("Longest:", max(words, key=len))print("Shortest:", min(words, key=len))
Output
Longest: handling
Shortest: easy

Line by line

Lines 3-4

key=len compares words by their length; on a tie, the first such word wins.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Vowel or consonant

Vowel or consonant

EasyString Programs · 6 of 106

Write a Python program to test whether a letter is a vowel or a consonant.

Input
"e", "K", "3"
Output
e -> vowel
K -> consonant
3 -> not a single letter

Approach

  1. Reject non-letters, then check membership in “aeiou”.

Solution

Python
def kind(ch):    if not ch.isalpha() or len(ch) != 1:        return "not a single letter"    return "vowel" if ch.lower() in "aeiou" else "consonant" for ch in ["e", "K", "3"]:    print(ch, "->", kind(ch))
Output
e -> vowel
K -> consonant
3 -> not a single letter

Line by line

Lines 2-3

Digits, symbols and longer strings are rejected first.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Count occurrences of a substring

Count occurrences of a substring

EasyString Programs · 5 of 106

Write a Python program to count how many times a substring occurs in a string.

Input
text = "the cat sat on the mat with the hat", sub = "the"
Output
3
4

Approach

  1. Use str.count().

Solution

Python
text = "the cat sat on the mat with the hat"print(text.count("the"))print(text.count("at"))
Output
3
4

Line by line

Line 2

count() counts non-overlapping occurrences.

Note

Because matches do not overlap, "aaaa".count("aa") is 2, not 3.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Reverse a string if its length is a multiple of 4

Reverse a string if its length is a multiple of 4

EasyString Programs · 4 of 106

Write a Python program to reverse a string if its length is a multiple of 4; otherwise return it unchanged.

Input
"Python", "sqatools"
Output
Python -> Python
sqatools -> slootaqs

Approach

  1. Check len(text) % 4 == 0, then reverse with [::-1].

Solution

Python
for text in ["Python", "sqatools"]:    result = text[::-1] if len(text) % 4 == 0 else text    print(text, "->", result)
Output
Python -> Python
sqatools -> slootaqs

Line by line

Line 2

“sqatools” has 8 characters, so it is reversed; “Python” has 6, so it is not.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Four copies of the last two characters

Four copies of the last two characters

EasyString Programs · 3 of 106

Write a Python program to make a string of 4 copies of the last two characters of a string (length must be at least 2).

Input
"Python"
Output
onononon

Approach

  1. Slice the last two characters and repeat them with * 4.

Solution

Python
text = "Python"if len(text) >= 2:    print(text[-2:] * 4)else:    print("String must have at least 2 characters")
Output
onononon

Line by line

Line 3

text[-2:] is “on”; multiplying a string repeats it.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Length of the longest string in a list

Length of the longest string in a list

EasyString Programs · 2 of 106

Write a Python program that returns the length of the longest string in a list.

Input
["python", "is", "readable", "fun"]
Output
8 | 8 | readable

Approach

  1. Compare lengths in a loop, or use max() with len.

Solution

Python
words = ["python", "is", "readable", "fun"]longest = 0for w in words:    if len(w) > longest:        longest = len(w)print(longest, "|", max(len(w) for w in words), "|", max(words, key=len))
Output
8 | 8 | readable

Line by line

Lines 3-5

Keep the biggest length seen so far.

Line 6

max(len(w) for w in words) does the same in one line; max(words, key=len) returns the word itself.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

First and last 2 characters

First and last 2 characters

EasyString Programs · 1 of 106

Write a Python program to build a string from the first 2 and the last 2 characters of a string. If the string is shorter than 2 characters, return an empty string.

Input
"Sqatools", "Py", "S"
Output
'Sqatools' -> 'Sqls'
'Py' -> 'PyPy'
'S' -> ''

Approach

  1. Check the length first; then join two slices.

Solution

Python
def ends(text):    if len(text) < 2:        return ""    return text[:2] + text[-2:] for t in ["Sqatools", "Py", "S"]:    print(repr(t), "->", repr(ends(t)))
Output
'Sqatools' -> 'Sqls'
'Py' -> 'PyPy'
'S' -> ''

Line by line

Lines 2-3

Strings shorter than 2 characters return an empty string, as the task asks.

Line 4

text[:2] is the first two characters and text[-2:] the last two.

Note

For “Py” the two slices overlap, so the result is “PyPy”.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Round every number and sum

Python Practice › List Programs › Program 99

Round every number and sum

EasyList Programs · 99 of 100

Write a Python program to round every number in a list and print the sum of the rounded numbers multiplied by the list length.

Input
[22.4, 4.0, -16.22, -9.1, 11.0, -12.22, 14.2, -5.2, 17.5]
Output
[22, 4, -16, -9, 11, -12, 14, -5, 18]
243

Approach

  1. Round each value with round(), add them, multiply by the length.

Solution

Python
numbers = [22.4, 4.0, -16.22, -9.1, 11.0, -12.22, 14.2, -5.2, 17.5]rounded = [round(n) for n in numbers]print(rounded)print(sum(rounded) * len(numbers))
Output
[22, 4, -16, -9, 11, -12, 14, -5, 18]
243

Line by line

Line 2

round(17.5) is 18 and round(-12.22) is -12; ties go to the even number.

Note

The sum of the rounded numbers is 27; multiplied by the 9 items it is 243.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Decode a run-length encoded list

Python Practice › List Programs › Program 98

Decode a run-length encoded list

MediumList Programs · 98 of 100

Write a Python program to decode a run-length encoded list, where [n, x] means x repeated n times.

Input
[[2, 1], 2, 3, [2, 4], 5, 1]
Output
[1, 1, 2, 3, 4, 4, 5, 1]

Approach

  1. Expand [n, x] pairs; copy plain items.

Solution

Python
encoded = [[2, 1], 2, 3, [2, 4], 5, 1]decoded = []for item in encoded:    if isinstance(item, list):        count, value = item        decoded.extend([value] * count)    else:        decoded.append(item)print(decoded)
Output
[1, 1, 2, 3, 4, 4, 5, 1]

Line by line

Lines 5-6

[value] * count repeats the value.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Remove repeated dictionaries

Python Practice › List Programs › Program 97

Remove repeated dictionaries

EasyList Programs · 97 of 100

Write a Python program to remove repeated dictionaries from a list.

Input
[{"Hello": 5}, {"student": 7}, {"are": 3}, {"learning": 8}, {"Hello": 5}, {"Language": 8}, {"are": 3}]
Output
[{'Hello': 5}, {'student': 7}, {'are': 3}, {'learning': 8}, {'Language': 8}]

Approach

  1. Use a set of each dict’s items (as a frozenset) to remember what was seen.

Solution

Python
data = [{"Hello": 5}, {"student": 7}, {"are": 3}, {"learning": 8}, {"Hello": 5}, {"Language": 8}, {"are": 3}]seen = set()result = []for d in data:    key = frozenset(d.items())    if key not in seen:        seen.add(key)        result.append(d)print(result)
Output
[{'Hello': 5}, {'student': 7}, {'are': 3}, {'learning': 8}, {'Language': 8}]

Line by line

Line 4

frozenset(d.items()) is a hashable fingerprint of the dict, so the check is fast even for long lists.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs