Overwrite a file

Overwrite a file

EasyFile Handling Programs · 2 of 38

Write a Python program to overwrite the content of an existing file.

Output
new content

Approach

  1. Opening in mode “w” empties the file before writing.

Solution

Python
with open("data.txt", "w") as f:    f.write("old content\n") with open("data.txt", "w") as f:    f.write("new content\n") print(open("data.txt").read())
Output
new content

Line by line

Lines 4-5

The second “w” open erased “old content” before writing.

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Read a file in read mode

Read a file in read mode

EasyFile Handling Programs · 1 of 38

Write a Python program to read a file in reading mode.

Output
Python file handling
is easy with open()

Approach

  1. Create a sample file, then open it with mode “r” inside a with block and read it.

Solution

Python
with open("notes.txt", "w") as f:    f.write("Python file handling\nis easy with open()\n") with open("notes.txt", "r") as f:    content = f.read()print(content)
Output
Python file handling
is easy with open()

Line by line

Lines 1-2

Creates the sample file so the program runs anywhere.

Line 4

Mode “r” (the default) opens the file for reading; with closes it automatically.

Line 5

read() returns the whole file as one string.

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

All permutations of a string

All permutations of a string

EasyFunction Programs · 39 of 39

Write a Python function that returns all permutations of a string, without itertools.

Input
"abc"
Output
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Approach

  1. Recursion: fix each character first and permute the rest.

Solution

Python
def permutations(text):    if len(text) <= 1:        return [text]    result = []    for i, ch in enumerate(text):        for rest in permutations(text[:i] + text[i + 1:]):            result.append(ch + rest)    return result print(permutations("abc"))
Output
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Line by line

Lines 2-3

A string of 0 or 1 characters has one permutation.

Lines 5-7

Each character goes first, followed by every permutation of the remaining characters.

Learn the concept

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

More function programs

← All 39 Function Programs

Integer to words

Integer to words

MediumFunction Programs · 38 of 39

Write a Python function that converts an integer from 0 to 999 into English words.

Input
0, 15, 42, 305, 999
Output
0 -> zero
15 -> fifteen
42 -> forty-two
305 -> three hundred and five
999 -> nine hundred and ninety-nine

Approach

  1. Handle hundreds, then tens, then units with lookup lists.

Solution

Python
ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",        "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",        "seventeen", "eighteen", "nineteen"]TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] def to_words(n):    if n < 20:        return ONES[n]    if n < 100:        return TENS[n // 10] + ("" if n % 10 == 0 else "-" + ONES[n % 10])    rest = n % 100    return ONES[n // 100] + " hundred" + ("" if rest == 0 else " and " + to_words(rest)) for n in [0, 15, 42, 305, 999]:    print(n, "->", to_words(n))
Output
0 -> zero
15 -> fifteen
42 -> forty-two
305 -> three hundred and five
999 -> nine hundred and ninety-nine

Line by line

Lines 7-8

Numbers below 20 have their own names.

Lines 9-10

Tens plus an optional unit, joined with a hyphen.

Lines 11-12

Hundreds reuse the same function for the remainder.

Learn the concept

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

More function programs

← All 39 Function Programs

Validate a mobile number

Validate a mobile number

EasyFunction Programs · 37 of 39

Write a Python function to check whether a mobile number is valid: 10 digits starting with 6, 7, 8 or 9 (optionally with +91).

Input
"9876543210", "+91 9123456789", "12345"
Output
9876543210 True
+91 9123456789 True
12345 False
5876543210 False

Approach

  1. A regular expression describes the pattern.

Solution

Python
import re def is_valid_mobile(number):    return bool(re.fullmatch(r"(\+91[\s-]?)?[6-9]\d{9}", number.strip())) for n in ["9876543210", "+91 9123456789", "12345", "5876543210"]:    print(n, is_valid_mobile(n))
Output
9876543210 True
+91 9123456789 True
12345 False
5876543210 False

Line by line

Line 4

fullmatch requires the whole string to fit, so extra characters fail.

Learn the concept

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

More function programs

← All 39 Function Programs

Length of the last word

Length of the last word

EasyFunction Programs · 36 of 39

Write a Python function that returns the length of the last word in a string.

Input
"Learning Python is fun   "
Output
3 0

Approach

  1. split() ignores trailing spaces.

Solution

Python
def last_word_length(text):    words = text.split()    return len(words[-1]) if words else 0 print(last_word_length("Learning Python is fun   "), last_word_length("   "))
Output
3 0

Learn the concept

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

More function programs

← All 39 Function Programs

Search for words in a string

Search for words in a string

EasyFunction Programs · 35 of 39

Write a Python function that reports which of the given words appear in a string.

Input
"Python makes testing easy", ["testing", "java", "easy"]
Output
{'testing': True, 'java': False, 'easy': True}

Approach

  1. Compare lower-case words.

Solution

Python
def search(text, words):    found = set(text.lower().split())    return {w: w.lower() in found for w in words} print(search("Python makes testing easy", ["testing", "java", "easy"]))
Output
{'testing': True, 'java': False, 'easy': True}

Learn the concept

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

More function programs

← All 39 Function Programs

Add two binary numbers

Add two binary numbers

EasyFunction Programs · 34 of 39

Write a Python function to add two binary numbers given as strings.

Input
"1011", "111"
Output
10010

Approach

  1. Convert with int(x, 2), add, convert back with bin().

Solution

Python
def add_binary(a, b):    return bin(int(a, 2) + int(b, 2))[2:] print(add_binary("1011", "111"))
Output
10010

Line by line

Line 2

[2:] drops the “0b” prefix.

Learn the concept

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

More function programs

← All 39 Function Programs

Library management system

Library management system

MediumFunction Programs · 33 of 39

Write a Python program with functions to add, issue, return and list books in a library.

Output
Issued 'Clean Code'
'Clean Code' is not available
Returned 'Clean Code'
Available: ['Python Basics', 'Clean Code', 'Atomic Habits']

Approach

  1. Store each book’s availability in a dictionary.

Solution

Python
books = {} def add_book(title):    books[title] = True                # True means available def issue(title):    if books.get(title):        books[title] = False        return f"Issued '{title}'"    return f"'{title}' is not available" def return_book(title):    if title in books and not books[title]:        books[title] = True        return f"Returned '{title}'"    return f"'{title}' was not issued" def available():    return [t for t, ok in books.items() if ok] for t in ["Python Basics", "Clean Code", "Atomic Habits"]:    add_book(t)print(issue("Clean Code"))print(issue("Clean Code"))print(return_book("Clean Code"))print("Available:", available())
Output
Issued 'Clean Code'
'Clean Code' is not available
Returned 'Clean Code'
Available: ['Python Basics', 'Clean Code', 'Atomic Habits']

Line by line

Lines 6-9

A book can be issued only while it is available.

Lines 12-15

Returning works only for books that were issued.

Learn the concept

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

More function programs

← All 39 Function Programs

Reverse an integer

Reverse an integer

EasyFunction Programs · 32 of 39

Write a Python function to reverse an integer, keeping the sign.

Input
1234, -560
Output
4321 -65

Approach

  1. Reverse the digits of the absolute value and restore the sign.

Solution

Python
def reverse_int(n):    sign = -1 if n < 0 else 1    return sign * int(str(abs(n))[::-1]) print(reverse_int(1234), reverse_int(-560))
Output
4321 -65

Line by line

Line 2

The sign is stored separately because “-” would end up at the end of the reversed text.

Learn the concept

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

More function programs

← All 39 Function Programs