Letter counter II [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
A couple days ago, I made a program that allowed me to pick a letter from a string and it would tell me how many times a chosen letter appeared. Now I want to use that code to create a program that takes all the letters and counts how many times each letter appears. For example, if I put "dog" in as my string, I would want the program to say that d appears once, o appears once, and g appears once. Here is my current code below.
from collections import Counter
import string
pickedletter= ()
count = 0
word = ()
def count_letters(word):
global count
wordsList = word.split()
for words in wordsList:
if words == pickedletter:
count = count+1
return count
word = input("what do you want to type? ")
pickedletter = input("what letter do you want to pick? ")
print (word.count(pickedletter))

from collections import Counter
def count_letters(word):
counts = Counter(word)
for char in sorted(counts):
print char, "appears", counts[char], "times in", word

I'm not sure why you're importing anything for this, especially Counter. This is the approach I would use:
def count_letters(s):
"""Count the number of times each letter appears in the provided
specified string.
"""
results = {} # Results dictionary.
for x in s:
if x.isalpha():
try:
results[x.lower()] += 1 # Case insensitive.
except KeyError:
results[x.lower()] = 1
return results
if __name__ == '__main__':
s = 'The quick brown fox jumps over the lazy dog and the cow jumps over the moon.'
results = count_letters(s)
print(results)

Related

Adding Random Characters Between Characters in a String (Python) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to add random letters after each letter in a given range, but they aren't in complete randomness.
def add_letters(org,num):
new_word = ''
for i in org:
randomLetter = random.choice(string.ascii_letters) * num
new_word += i
new_word += randomLetter
return new_word
original = 'Hello!'
for num in range(1,5):
#scramble the word using 'num' extra characters
scrambled = add_letters(original,num)
#output
print("Adding",num,'random characters to',original,'->',scrambled)
some of the results will have the same letter repeating multiple times like "HAAAAeiiiilzzzzlBBBBoSSSS!jjjj". Instead, they should be random.
You used *sum, which only generate randomLetter once and repeat the result letter for sum times. It's not repeat the random generation. So the result repeated.
It should be a loop or list-comprehension to generate mutiple randomLetter.
fixed code:
import random
import string
def add_letters(org,num):
new_word = ''
for i in org:
randomLetter = "".join(random.choice(string.ascii_letters) for _ in range(num))
new_word += i
new_word += randomLetter
return new_word
original = 'Hello!'
for num in range(1,5):
#scramble the word using 'num' extra characters
scrambled = add_letters(original,num)
#output
print("Adding",num,'random characters to',original,'->',scrambled)
result:
Adding 1 random characters to Hello! -> HNemldlgos!z
Adding 2 random characters to Hello! -> HVTeGYlYLlxdonV!GM
Adding 3 random characters to Hello! -> HqjbeQyOlgfHlAwqoyCj!PRq
Adding 4 random characters to Hello! -> HyFoLeyHUzlExGelVLlAoOhyz!EuzW

Alphabatic Anagrams doesn't work with words that contains letters with multiple occurence [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Hello how are you? I have a challenge https://www.codewars.com/kata/53e57dada0cb0400ba000688/solutions/python and I've stuck on it for a 2 days, I created the first solution but it was slow(using itertools.permutations), and then I've make this block of code.
import math
def listPosition(word):
n = 0
wlsort = list(word)
wlsort.sort()
wcopy = word
while wcopy:
for i in range(wlsort.index(wcopy[0])):
n += math.factorial(len(wlsort) - 1)
wlsort.pop(wlsort.index(wcopy[0]))
wcopy = wcopy[1:]
return n + 1
but it doesn't work with words like test bookkeeper, Do you have any hints, or idea on how to solve it?
I think my problem is that when I have a word like car it will brute-force it like ->
acr, arc...
and if i have caar it will brute-force it like ->
aacr, aarc and it doesn't do acar because it is brute-forcing alphabetically.
Here is my attempt. It's quite straightforward, if you read the req. carefully. Please let me know if you have any questions.
from math import factorial as fact
def listPosition(word):
count = 0
while len(word):
first = word[0]
uniqs = set(word)
possibles = fact(len(word))
for ch in uniqs:
possibles /= fact(word.count(ch))
for ch in uniqs:
if ch < first:
count += possibles/len(word) * word.count(ch)
word = word[1:]
return count + 1

Sort the sequence alphabetically-Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I want to write a python function that accepts a hyphen separated sequence of colors as input and returns the colors in a hyphen separated sequence after sorting them alphabetically
constraint: All colors will be completely in either lower case or upper case
sample input: green-red-yellow-black-white
sample output: black-green-red-white-yellow
My code -
my_str = input("Enter a string: ")
words = [word.lower() for word in my_str.split()]
words.sort()
print("The sorted words are:")
for word in words:
print(word)
This works -
def str_sort(string):
b = string.split('-')
b.sort()
c = '-'.join(b)
return c
a = input('Enter a sequence of colors separated with hyphen: ')
str_sort(a)
This will solve your problem:
inputs = "green-red-yellow-black-white"
def sort_inputs(inputs):
inputs_list = inputs.split('-')
sorted_input = sorted(inputs_list)
final = "-".join(term for term in sorted_input)
return final
final = sort_inputs(inputs)
print(final)

Python- writing sentence in given format [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a file with one sentence. I let the user choose the number of 'rows' and 'columns'. I want to check how many times I can write the sentence in this kind of table without splitting words.Now I would like the text to form like this:
Input:
rows=3
columns=10
setence from file: Cat has dog.
Output:
Cat has***
dog. Cat**
has dog.**
The program can't split words and in places where they can't fit place stars. Here is the part of the code I did but I feel I am not going the good direction.
My questions:
1. How can I improve my code?
2. How to make it count chars but also words?
3. General tips for this task.
My code:
import sys
columns, rows, path = sys.argv[1:]
columns=int(columns)
rows=int(rows)
file=open(path,"r")
text=file.read()
list=list(text.split())
length=len(list)
for i in range(length):
k=len(lista[i])
if k<=columns:
print(list[i], end=" ")
else:
print("*")
This was tougher than I thought it would be. There might be an easier solution out there but you can try this:
list_of_words = text.split()
current_character_count_for_row = 0
current_string_for_row = ""
current_row = 1
how_many_times_has_sentence_been_written = 0
is_space_available = True
# Keep going until told to stop.
while is_space_available:
for word in list_of_words:
# If a word is too long for a row, then return false.
if len(word) > columns:
is_space_available = False
break
# Check if we can add word to row.
if len(word) + current_character_count_for_row < columns:
# If at start of row, then just add word if short enough.
if current_character_count_for_row == 0:
current_string_for_row = current_string_for_row + word
current_character_count_for_row += len(word)
# otherwise, add word with a space before it.
else:
current_string_for_row = current_string_for_row +" " + word
current_character_count_for_row += len(word) + 1
# Word doesn't fit into row.
else:
# Fill rest of current row with *'s.
current_string_for_row = current_string_for_row + "*"*(columns - current_character_count_for_row)
# Print it.
print(current_string_for_row)
# Break if on final row.
if current_row == rows:
is_space_available = False
break
# Otherwise start a new row with the word
current_row +=1
current_character_count_for_row = len(word)
current_string_for_row = word
if current_row > rows:
is_space_available = False
break
# Have got to end of words. Increment the count, unless we've gone over the row count.
if is_space_available:
how_many_times_has_sentence_been_written +=1
print(how_many_times_has_sentence_been_written)

Find most frequent group of 3 words in a sentence [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Suppose I have a text like
text="I came from the moon. He went to the other room. She went to the drawing room."
Most Frequent group of 3 words here is "went to the"
I know how to find most frequent bigram or trigram but I am stuck in this.I want to find this solution without using NLTK library.
import string
text="I came from the moon. He went to the other room. She went to the drawing room."
for character in string.punctuation:
text = text.replace(character, " ")
while text != text.replace(" ", " "):
text = text.replace(" ", " ")
text = text.split(" ")
wordlist = []
frequency_dict = dict()
for i in range(len(text)-3):
wordlist.append([text[i], text[i+1], text[i+2]])
for three_words in wordlist:
frequency= wordlist.count(three_words)
frequency_dict[", ".join(three_words)] = frequency
print max(frequency_dict, key=frequency_dict.get), frequency_dict[max(frequency_dict, key=frequency_dict.get)]
Output: went, to, the 2
Unfortunately lists are not hashable. Otherwise it would help to create a set of the three_words items.
nltk makes this problem trivial, but seeing as you don't want such a dependency, I have included a simple implementation using only core libraries. The code works on python2.7 and python3.x, and uses collections.Counter to count frequencies of n-grams. Computationally, it is O(NM) where N is the number of words in the text and M is the number of n-grams being counted (so if one were to count uni and bigrams, M = 2).
import collections
import re
import sys
import time
# Convert a string to lowercase and split into words (w/o punctuation)
def tokenize(string):
return re.findall(r'\w+', string.lower())
def count_ngrams(lines, min_length=2, max_length=4):
lengths = range(min_length, max_length + 1)
ngrams = {length: collections.Counter() for length in lengths}
queue = collections.deque(maxlen=max_length)
# Helper function to add n-grams at start of current queue to dict
def add_queue():
current = tuple(queue)
for length in lengths:
if len(current) >= length:
ngrams[length][current[:length]] += 1
# Loop through all lines and words and add n-grams to dict
for line in lines:
for word in tokenize(line):
queue.append(word)
if len(queue) >= max_length:
add_queue()
# Make sure we get the n-grams at the tail end of the queue
while len(queue) > min_length:
queue.popleft()
add_queue()
return ngrams
def print_most_frequent(ngrams, num=10):
for n in sorted(ngrams):
print('----- {} most common {}-grams -----'.format(num, n))
for gram, count in ngrams[n].most_common(num):
print('{0}: {1}'.format(' '.join(gram), count))
print('')
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python ngrams.py filename')
sys.exit(1)
start_time = time.time()
with open(sys.argv[1]) as f:
ngrams = count_ngrams(f)
print_most_frequent(ngrams)
elapsed_time = time.time() - start_time
print('Took {:.03f} seconds'.format(elapsed_time))
text="I came from the moon. He went to the other room. She went to the drawing room."
fixed_text = re.sub("[^a-zA-Z ]"," ",text)
text_list = fixed_text.split()
print Counter(" ".join(text_list[i:i+3]) for i in range(len(text_list)-3)).most_common(1)
I guess ... maybe?
>>> text="I came from the moon. He went to the other room. She went to the drawi
ng room."
>>> fixed_text = re.sub("[^a-zA-Z ]"," ",text)
>>> text_list = fixed_text.split()
>>> print Counter(" ".join(text_list[i:i+3]) for i in range(len(text_list)-3)).most_common(1)
[('went to the', 2)]
>>>

Categories

Resources