Skip to Main Content
Blog

Count Words in Python

Count Words in Python

def main():
	"""
	Removes duplicate English letters from a string.
	"""

	text = input("Enter string: ")
	result = deduplicate(text)
	print(result)


def deduplicate(text: str):
	builder = ""
	counts = frequency(text)

	for i in range(len(text)):
		ch = text[i]
		lc = ch.lower()
		if "a" <= lc <= "z":
			countsIndex = ord(lc) - ord("a")
			if counts[countsIndex] <= 0:
				continue
			counts[countsIndex] *= -1
		builder += ch

	return builder


def frequency(text: str):
	"""
	Counts the frequency of English letter in a string.
	"""

	# Represent the frequency of 26 English letters in an array
	counts = [0] * 26

	# Count the occurrences of each lower cased English letter
	for c in text:
		c = c.lower()
		if "a" <= c < "z":
			counts[ord(c) - ord("a")] += 1

	return counts


if __name__ == "__main__":
	main()
def main():
	"""
	Removes duplicate characters from a string.
	"""

	txt = input("Enter string: ")

	unique: list[str] = []
	visited: set[str] = set()
	for c in txt:
		if c.isspace():
			unique.append(c)
			continue
		if c not in visited:
			unique.append(c)
			visited.add(c)

	txt = "".join(unique)
	print(txt)


if __name__ == "__main__":
	main()