Reputation: 3
I'm new to python and I am trying to write a program that will calculate the average character in a given word.
This is the assignment: Write a program that accepts a word (a sequence of letters) and return the average character.
And the program should flow in this order: Turn the string into a list of characters. Use ord() function to convert from character to number. Calculate the average value of the the number. Use chr() to convert from number back to character.
I think I am supposed to take an input and then find the integer values using ord() function, and then find the average of those integers.
This is what I have written so far:
word = input('Enter a word here:')
list(word)
print(list(word))
for char in range(len(word)):
print(ord(word[char]))
The program can turn the word into a list of characters and also display those integer values. But now, I'm lost and not sure where to go to find the average of these numbers. Can someone point me in the right direction like maybe a website that explains how to do it or something like that.
Upvotes: 0
Views: 951
Reputation: 1179
I think this is what you want:
word = 'hello'
chars = [ord(c) for c in word]
avg = sum(chars)//len(chars)
avg_char = chr(avg)
For 'hello', the average character is 'j'.
Upvotes: 0
Reputation: 57033
The Pythonic way is to use either list comprehension or mapping.
word = 'hello, world'
With mapping, you tell function map
to apply ord
to each character:
chr(sum(map(ord, word)) // len(word))
#'`'
With list comprehension, you apply the function yourself:
chr(sum(ord(x) for x in word) // len(word))
#'`'
The mapping solution is about twice as fast as the comprehension.
Upvotes: 0
Reputation: 875
What I understood is something like this:
word = input('Enter a word here:')
sum_word = 0
for character in word:
sum_word += ord(character)
average = chr(sum_word//len(word))
print(average)
Just got a doubt about average
, but let me know if it isn't right and I'll change it
Upvotes: 1