Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check whether the Average Character of the String is present or not in Python
When working with strings in Python, you might need to find the "average character" based on ASCII values. This involves calculating the average of all character ASCII values and determining if that average corresponds to an actual character in the string.
The average character is found by taking the floor of the average ASCII values of all characters in the string. If this average ASCII value corresponds to a character present in the original string, we return that character.
Example
Let's say we have the string s = "pqrst". The ASCII values are:
- p = 112
- q = 113
- r = 114
- s = 115
- t = 116
The average is (112 + 113 + 114 + 115 + 116) / 5 = 570 / 5 = 114, which corresponds to 'r'.
Algorithm Steps
To solve this problem, we follow these steps −
- Initialize total := 0
- For each character in the string, add its ASCII value to total
- Calculate avg := floor(total / length of string)
- Convert the average back to a character
- Check if this character exists in the original string
Implementation
def find_average_character(s):
total = 0
# Calculate sum of ASCII values
for ch in s:
total += ord(ch)
# Calculate average and convert to character
avg = total // len(s) # Floor division
avg_char = chr(avg)
# Check if average character exists in string
if avg_char in s:
return avg_char
else:
return None
# Test with example
s = "pqrst"
result = find_average_character(s)
print(f"String: {s}")
print(f"Average character: {result}")
String: pqrst Average character: r
Alternative Implementation
Here's a more concise version using built-in functions ?
def find_average_character_compact(s):
avg_ascii = sum(ord(ch) for ch in s) // len(s)
avg_char = chr(avg_ascii)
return avg_char if avg_char in s else None
# Test with multiple examples
test_strings = ["pqrst", "abc", "hello", "xyz"]
for string in test_strings:
result = find_average_character_compact(string)
avg_ascii = sum(ord(ch) for ch in string) // len(string)
print(f"String: '{string}' | Average ASCII: {avg_ascii} | Result: {result}")
String: 'pqrst' | Average ASCII: 114 | Result: r String: 'abc' | Average ASCII: 98 | Result: b String: 'hello' | Average ASCII: 104 | Result: h String: 'xyz' | Average ASCII: 121 | Result: y
Key Points
- Use
ord()to get ASCII value of a character - Use
chr()to convert ASCII value back to character - Floor division
//is equivalent toint(floor()) - Check if the computed average character exists in the original string
Conclusion
Finding the average character involves calculating the mean ASCII value and checking if the resulting character exists in the original string. This technique can be useful in text processing and string analysis applications.
