aboutsummaryrefslogtreecommitdiff
path: root/challenge-341/spadacciniweb/python/ch-2.py
blob: a0d3d07e678c56bce759b399f9fde5d3c6c26315 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Task 2: Reverse Prefix
# Submitted by: Mohammad Sajid Anwar
# 
# You are given a string, $str and a character in the given string, $char.
# Write a script to reverse the prefix upto the first occurrence of the given $char in the given string $str and return the new string.
# 
# Example 1
# Input: $str = "programming", $char = "g"
# Output: "gorpmming"
# 
# Reverse of prefix "prog" is "gorp".
# 
# Example 2
# Input: $str = "hello", $char = "h"
# Output: "hello"
# 
# Example 3
# Input: $str = "abcdefghij", $char = "h"
# Output: "hgfedcbaj"
# 
# Example 4
# Input: $str = "reverse", $char = "s"
# Output: "srevere"
# 
# Example 5
# Input: $str = "perl", $char = "r"
# Output: "repl"

def reverse_prefix(str, char):
    strings = list(str)
    new_str = ''
    for n in (range(len(str))):
        letter = strings.pop(0);
        new_str += letter
        if letter == char:
            new_str = new_str[::-1]
            break
    new_str += ''.join( strings )

    print("'%s' '%s' -> '%s'" % (str, char, new_str) )

if __name__ == "__main__":
    str = "programming"
    char = "g"
    reverse_prefix( str, char )

    str = "hello"
    char = "h"
    reverse_prefix( str, char )

    str = "abcdefghij"
    char = "h"
    reverse_prefix( str, char )

    str = "reverse"
    char = "s"
    reverse_prefix( str, char )

    str = "perl"
    char = "r"
    reverse_prefix( str, char )