Python- writing sentence in given format [closed] - python

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)

Related

A function similar to split() [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 last year.
Improve this question
I was wondering what the A != "" does in this code.
def mysplit(strng):
A = ""
B = []
for i in strng:
if i != " ":
A += i
elif A != "":
B.append(A)
A = ""
# Append last word
if A != "":
B.append(A)
return(B)
This is the code that I found for a uni project that i need, but that piece of code doesn't make sense to me, isnt it just empty? how are you gonna get an empty character in your text apart from the spaces?
also, do strings have positions?
Explanation:
What this function will do is accept a string as an argument, and then loop through each character of the string.
The first if will add character by character to A until it reaches a space and when this occurs it will dump the contents of A into B as a [list], which will be a full word, and then RESET A to '', that way it will continue to read char by char the next word.
By the end of the loop, B will contain each word of the string as items in a list and return.
To answer your other question, yes strings do have index positions. If you
print('Hello World'[0:5])
This will return: Hello
Code:
def mysplit(strng):
A = ""
B = []
for i in strng: #Loop through each char in string
if i != " ": #if char is not a space
A += i #add character to A
elif A != "": #if A is not empty
B.append(A) #add whatever is in A to B as a list (full word)
A = "" #resets A to be empty
if A != "": #if A is empty
B.append(A)
return B #return is a statement, so it doesn't require parenthesis.
Yes, strings have index from 0 to n-1 just like in a string.
Eg: A = "abcd", print(a[2]) //output: "c"
As for your code, i iterates through every element in the input string, and it is appended to A if i is not a "space". When it is a "space", A is appended to B list and A is cleared in order to get the next word. For the last word, since there is no space in the end, the string A does not get appended to B list, so it is done separately outside the for loop.

Take in integer and string using input() and check for conditions [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 3 years ago.
Improve this question
I needed help with this problem here in python:
Write a program which accepts an integer N and N strings each on a newline. Check for the below conditions and perform the respective operations:
The string contains only one word then capitalize the whole string
The string contains exactly 2 words capitalize only the first character of each word
The string contains more than two words toggle case of the string
Your task is to print each string in a newline after performing the respective operations.
Input Format:
The first line will contain an integer N, specifying the number of strings
The next N lines will contain one string each
Output Format:
String after performing the respective operation in a newline.
Example #1:
Input:
3 #number of input words
Hello #1st input
My name is #2nd input
adam smith #3rd input
Output:
HELLO
mY NAME IS
Adam smith
This solution will work:
num=int(input())
words=[]
for a in range(0,num):
words.append(input())
for word in words:
if len(word.split())==1:
print(word.upper())
elif len(word.split())==2:
print(word.title())
elif len(word.split())>2:
print(word.swapcase())
if you are trying to attempt a HackerRank challenge or any other code challenge, i would strongly recommend first building small programs then attempting those.
It seems that you would have to look through a multi-line string to get the input.
So a sample string would look something like:
sample = """
3
Hello
My name is
adam smith
"""
Now, to find the number of words in one line of each string...
There is a built-in string function called split(), but I'm going to do the basic version:
def toWords(string):
newlist = [] # create a list we can add things to with ".append()"
newstr = '' # initial string
for i in string:
if i == ' ': # When we come across a space
newlist.append(newstr) # Add what's been accumulated to list
newstr = '' # Start over
else:
newstr += i # Accumulate
if newstr:
newlist.append(newstr)
return newlist # Finally, return the value
We also need a way to split up the multi-line string:
my_list = sample.split('\n') # where '\n' is the newline character
Last, we add the rules:
def all(string):
acc = "" #acc for accumulator
my_list = string.split('\n')
toggle = 1
number = int(my_list[0])
for i in my_list[1:]:
if len(toWords(i)) == 1:
acc += toWords(i)[0].lower() + ' '
elif len(toWords(i)) == 2:
acc += toWords(i)[0].capitalize() + toWords(i)[1].capitalize() + ' '
else:
for char in i:
toggle = toggle * -1
if toggle == 1:
acc += char
acc += ' '
return acc

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)]
>>>

Letter counter II [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 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)

Printing out a word if it has a specific letter in it? [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 8 years ago.
Improve this question
How would i print out a word in a list or string that has a specific letter in it?
e.g.
Letter: e
Input: I need help with my program
need help
See how it printed out "need help" because those words have "e" in them? Help :)
My workaround:
a = input("Letter: ")
b = input("Input: ")
c = b.count(a)
print(c)
d = b.split()
for e in d:
print(e,end=" ")
Why not simply:
a = input("Letter: ")
b = input("Input: ")
words = b.split()
for word in words:
if a in word:
print(word)
You almost had it. In your for loop, now you just need a conditional.
A conditional is a statement which determines whether something is True or False.
You probably want:
for e in d:
if a in e:
print(e)
You can check if a character (or substring) is in a string using in:
letter = input("Letter: ")[0] # Limit to one character
words = input("Text: ").split()
for word in words:
if letter in word:
print(word, end=" ")
print() # Add newline
Addendum (see the comments):
To remove the final space, you can accumulate the words in a string and then remove it
letter = input("Letter: ")[0] # Limit to one character
words = input("Text: ").split()
output = ""
for word in words:
if letter in word:
output += word + " "
print(output.rstrip()) # Print without trailing whitespace
or (which I would discourage, because it makes the intention less obvious) check if you are encountering the last word and print a newline instead of the additional space (so you don't need the additional print().
letter = input("Letter: ")[0] # Limit to one character
words = input("Text: ").split()
for index in range(len(words)):
if letter in words[index]:
the_end = "\n" if index == len(words) - 1 else " " # Newline only if it is the last word
print(word, end=the_end)

Categories

Resources