easy
0 views

Substring Printer c-python convertion

Convert a C program that prints the last X characters of a string to equivalent Python code

Understand the Problem

Problem Statement

Convert the provided C code to Python so that the Python program executes successfully and produces the same output as the C version.

The C program reads a string and an integer X, then prints the last X characters of the string using pointer arithmetic.

Constraints

  • Input string length is at most 100 characters
  • Integer X is positive and less than or equal to string length
  • String contains only printable ASCII characters

Examples

Example 1
Input
Hello World
5
Output
World
Explanation

The last 5 characters of 'Hello World' are 'World'

Example 2
Input
Programming
4
Output
ming
Explanation

The last 4 characters of 'Programming' are 'ming'

Example 3
Input
test
2
Output
st
Explanation

The last 2 characters of 'test' are 'st'

Solution

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str[101];
    int len, X;
    scanf("%s%n%d", str, &len, &X);
    printf("%s", str + len - X);
    return 0;
}
Time:O(1)
Space:O(1)
Approach:

The C solution uses the %n format specifier in scanf to get the number of characters read into the string, which gives us the length. Then it uses pointer arithmetic (str + len - X) to point to the position X characters from the end of the string, and prints from that position to the end.

Key points:

  • %s reads the string
  • %n stores the number of characters read so far in len
  • %d reads the integer X
  • str + len - X creates a pointer to the desired starting position

Visual Explanation

Loading diagram...