blob: 47f77081f68e16cae20010dbf2a9226eb7e3796c (
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
"""
## Task 1: Percentage of Character
**Submitted by:** [Mohammad Sajid Anwar][0]
You are given a string, `$str` and a character `$char`.
Write a script to return the percentage, nearest whole, of given character in
the given string.
**Example 1**
```
Input: $str = "perl", $char = "e"
Output: 25
```
**Example 2**
```
Input: $str = "java", $char = "a"
Output: 50
```
**Example 3**
```
Input: $str = "python", $char = "m"
Output: 0
```
**Example 4**
```
Input: $str = "ada", $char = "a"
Output: 67
```
**Example 5**
```
Input: $str = "ballerina", $char = "l"
Output: 22
```
**Example 6**
```
Input: $str = "analitik", $char = "k"
Output: 13
```
[0]: https://manwar.org/
"""
PERCENTAGE_FACTOR = 100 # multiply the decimal value by 100 to get percentage
ROUNDING_THRESHOLD = 0.5 # ensure we are rounding half up, rather than even up
def percentage_of_character(string: str, char: str) -> int:
"""Return the percentage of given character in the given string.
Args:
string: The string to search for the character.
char: The character to search for in the string.
Returns:
The percentage of the character in the string, rounded to the nearest
whole number.
"""
# Get the length of the string for testing and calculating the percentage
string_length = len(string)
# Return 0 if the string or character are empty
if string_length == 0 or len(char) == 0:
return 0
# Count the number of times the character appears in the string
char_count = string.count(char)
# Calculate the percentage of the character in the string as a decimal
decimal_percentage = char_count / string_length
# Convert the decimal percentage to a percentage
percentage = decimal_percentage * PERCENTAGE_FACTOR
# Round the percentage to the nearest whole number (half up rounding)
rounded_percentage = int(percentage + ROUNDING_THRESHOLD)
return rounded_percentage
|