New to python, my assignment asks to ask user for input and then find and print the first letter of each word in the sentence
so far all I have is
phrase = raw_input("Please enter a sentence of 3 or 4 words: ")
^ That is all I have. So say the user enters the phrase "hey how are you" I am supposed to find and print the first letter of every word so it would print "hhay"
I know how to index if it is a string that the programmer types but not when a user inputs the data.
This does everything that Ming said in a single line.
You can very well understand this code if you read his explanation.
phrase = raw_input("Please enter a sentence of 3 or 4 words: ")
output = ''.join([x[0] for x in phrase.split()])
print output
Update related to comment (Considers only first 3 words):
output = ''.join([x[0] for x in phrase.split()])[:3]
Ignoring the last word (Total number of words doesn't matter)
output = ''.join([x[0] for x in phrase.split()])[:-1]
Here are a rough outline of the steps you can take. Since this is an assignment, I will leave actually assembling them into a working program up to you.
raw_input will produce a string.
If you have two strings, one in foo and one in bar, then you can call string.split as foo.split(bar), and the result of that will be a list of strings resulting from splitting the contents of foo by the separator bar. For example, 'a b c'.split(' ') == ['a', 'b', 'c'].
You can slice a string with brackets to retrieve particular characters from it, counting from zero in the leftmost position. For example, 'abcd'[0] == 'a'.
If you have a string foo and a list of strings bar, then you can call string.join as foo.join(bar) to produce a single string of the elements of foo glued together with bar. For example, 'x'.join(['a', 'b', 'c']) == 'axbxc'.
You can print the constructed output.
This is of course only one of many approaches you could take.
As an answer to your question "For the next one I have to join the first letters of only the first 3 words and ignore the 4th word. How do I do that?"
output = ''.join([x[0] for x in phrase.split()[0:3]])
If instead it is first character of all word but the last then use :
output = ''.join([x[0] for x in phrase.split()[0:len(phrase.split()) - 1]])
Related
Here is the what my function should do: take two strings as arguments(a string, and a letter, or letters) as input, and find the number of occurances of a letter or letters in a string. It has to be a function too. what am i doing wrong, it works correctly if I enter a letter, but if put multiple then the count is wrong?
Expected input: "hello" "ll"
Expected output: 1
my output: 0
def occurences(string1, string2):
count = 0
for word in string1:
for character in word:
count = count + 1
return count
first_string = input('Enter the first string: ')
second_string = input('Enter the second string: ')
occurance_var = occurences(first_string,second_string)
print(second_string,'ocures', occurance_var,'in', first_string)
#new_be_0905
you can use predefined string methods from python
you can do something like this
str1 = "Hello"
str2 = "ll"
print(str1.count(str2)) # Output: 1
Your function does not even use string2 argument, so it is unclear to me how it should work.
If you just need the result - find number of occurrences of substring in string, you can use string.count(substring)
If you want to understand how to implement this yourself - the approach that I would try is creating two variables - count and substr_index, then cycling through string and checking whether char == substr[substr_index]. If it is, add 1 to the substr_index. When the substr_index==len(substr), reset the variable and add 1 to the count
First of all, when you do
for word in string1:
this loop is iterating over each character in string1, not each word. If you want to iterate over each word individually, you would need to split the string.
Second, you are never actually doing a comparison in your loop. Notice how you never call string2 anywhere in occurrences(). Your program as it is is simply counting each letter, so I am unsure how you are getting 0.
The easiest method of comparing for a string with length greater than 1 would be to slice the string, doing something like
string[i:i+2]
Basically as the title says, I want the sentences of the user input to be capitalized, but not lose their capitalization in the process. The input's supposed to be two sentences that get separated by periods. The code I have here outputs them the sentences, but not joined or keeping the rest of the capitalization.
def main():
user_input = input("Enter the sentence you would like to be modified!: ").split(". ")
capitalized_sentences = [user_input[0].upper() + user_input[1:] for sentence in user_input]
recombined_sentences = ". ".join(capitalized_sentences)
Just edit the first character of each split to be upper:
# For this example, lets use this string. However, you would still use
# user_input = input("...") in your actual code
user_input = "for bar. egg spam."
# Turn the user_input into sentences.
# Note, this is assuming the user only is using one space.
# This gives us ["foo bar", "egg spam"]
sentences = user_input.split(". ")
# This is called a list comprehension. It's a way of writing
# a for-loop in Python. There's tons of documentation on it
# if you Google it.
#
# In this loop, the loop variable is "sentence". Please be mindful
# that it is a singular form of the word sentences.
#
# sentence[0].upper() will make the first letter in sentence uppercase
# sentence[1:] is the remaining letters, unmodified
#
# For the first iteration, this becomes:
# "f".upper() + "oo bar"
# "F" + "oo bar"
# "Foo bar"
capitalized_sentences = [sentence[0].upper() + sentence[1:]
for sentence
in sentences]
# At this point we have ["Foo bar", "Egg spam"]
# We need to join them together. Just use the same ". " we
# used to split them in the beginning!
#
# This gives us "Foo bar. Egg spam."
recombined_sentences = ". ".join(capitalized_sentences)
Replace "sentences" with your user_input bit
Note, there might be a "gotcha" if the user inputs sentences of a format you aren't expecting. For example, what if the user entered two spaces instead of one? Then the above code would try to capitalize a whitespace character. You would need to account for that.
It's very simple: You can use the String method upper() on a part of the string.
Here is a one-liner to do just that:
CapWord = "".join([c.upper() if i == 0 else c for i, c in enumerate([j for j in rawWord])])
Just replace CapWord and rawWord with respective values (you can change them to sentences / words depending on what you want to do.
What it does:
Iterates over an array with all the characters in the string and their respective enumeration (to avoid duplicate letters being capitalised as well) then checks if the char (c) has a number corresponding to the indexes to capitalise, and is converted to a string.
I am trying to solve this problem:
You are given n words. Some words may repeat. For each word, output its
number of occurrences. The output order should correspond with the
input order of appearance of the word. See the sample input/output for
clarification.
Note: Each input line ends with a "\n" character.
Input Format
The first line contains the integer, n .
The next n lines each contain a
word.
Output Format
Output 2 lines. On the first line, output the number of distinct words
from the input. On the second line, output the number of occurrences
for each distinct word according to their appearance in the input.
I have implemented a solution like this,
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
mySet = set()
myDict = {}
for i in range(n):
inp = input()[:-1]
if inp not in mySet:
mySet.add(inp)
myDict[inp] = 1
else:
myDict[inp] += 1
print(len(mySet))
# print(' '.join(list(map(str, myDict.values()))))
print(*myDict.values())
My strategy is as follows:
If the word is not in mySet, add it to the set and create a value-key pair on myDict with word as key and 1 as value.
If the word is in the set already, then increment the value of that word in the dictionary.
However, half of the test cases are successfull, but the rest are "Wrong Answer". So, I wonder, can anybody point out what do I miss to add to this code?
Your mistake is in inp = input()[:-1]. The [:-1] cuts off the word's last character. I guess you're trying to remove the newline character, but input() is already "stripping a trailing newline". Demo:
>>> [input() for _ in range(2)]
foo
bar
['foo', 'bar']
Simpler solution, btw:
from collections import Counter
ctr = Counter(input() for _ in range(int(input())))
print(len(ctr))
print(*ctr.values())
And for fun a tricky version of that (also gets accepted):
from collections import Counter
ctr = Counter(map(input, [''] * int(input())))
print(len(ctr))
print(*ctr.values())
Another one:
from collections import Counter
import sys
next(sys.stdin)
ctr = Counter(map(str.strip, sys.stdin))
print(len(ctr))
print(*ctr.values())
This one reads the whole lines, so here the strings do include the newline character. That wouldn't matter if all lines had it, but no, HackerRank commits the cardinal sin of not ending the last line with a newline. So I strip them off every line. Sigh.
In the problem, you don't need to use the set property and the way you are using input ie input()[::-1] is wrong as it is reversing the input which you have entered, ie for the input abc it is storing it as cba.
now to solve problem, as OP has figured out to take unique item use set, and to get the frequency of each word use dictionary. but using set is costly operation and dictionary can be used to get the unique word as it store unique keys which can be used to get the unique elments, and to get the frequency use the same operation as you are doing.
instead of adding key, value in dictionary by dict[key]=value better to update the current dictionary with inbuild method ie dict1.update(dict2) where dict1 is orignal dictionary and dict2 is new dictionary with key and value , dict2={key:value}, by this way you will keep the order of the element in dict.
to get the len of unique word , len of dictionary work ie len(dic) and to get the frequency of each word values need to printed ie print(*dic.values())
n = int(input())
dic = {}
for _ in range(n):
w = input()
if w in dic.keys():
dic[w]+=1
else:
dic.update({w:1})
print(len(dic.keys()))
print(*dic.values())
n=int(input())
word_list=[]
for i in range(n):
word_list.append(input())
New_word_list=[]
for element in word_list:
if element in New_word_list:
New_word_list=New_word_list
else:
New_word_list.append(element)
print(len(New_word_list))
for element in New_word_list:
print(word_list.count(element), end=" ")
Input:
10
cat
dog
dog
rabbit
cat
pig
horse
pig
pig
goat
Results:
6
2 2 1 3 1 1
The code written below should give results like below. For example, if input is ' Lion head and Snake tail', output should be - 'LHAST'.
Instead the result is 'LLLLL'. Please check my code. If possible please suggest better practice and help me with better code.
Code is as follows:
#ask for Input
name = input('Input words to make acroname :')
#make all in caps
name = name.upper()
#turn them in list
listname = name.split()
#cycle through
for namee in listname:
#Get the first letter & type in same line
print(name[0],end="")
print()
input (' press a key to move out' )
You may correct your code. Instead of print(name[0]) you should use print(namee[0]) as you want to print the first letter of the word, not the original name.
A good practice is to name the variables the more descriptive you can so as to avoid such typos.
If you want to print the acronym in same line I would suggest to use below code to get variable acronym with the desired output:
phrase = raw_input('Input words to make acronym:')
phrase = phrase.upper()
list_words = phrase.split()
acronym = [word[0] for word in list_words]
acronym = "".join(acronym)
print acronym
You could use str.join with a generator-expression for a one-line solution to the problem:
>>> name = "Lion head and Snake tail"
>>> ''.join(i[0].upper() for i in name.split())
'LHAST'
why?
Well if we start from inside the generator, we are iterating through name.split(). The .split method of a str returns a list of all the different strings which have been found by splitting on what is passed into the method. The default character is a space and since we want the words, this is fine for us.
We then say that for each word i in this list, take the first character from the string with: i[0]. We then convert this to upper case with str.upper().
Then, the final step is to join all these characters together and that is done with the str.join method.
Simply:
print ''.join([P[0] for P in input('Input words to make acroname :').upper().split()])
Use input('') for python 3 and raw_input('') for python 2
My code
beginning = input("What would you like to acronymize? : ")
second = beginning.upper()
third = second.split()
fourth = "".join(third[0])
print(fourth)
I can't seem to figure out what I'm missing. The code is supposed to the the phrase the user inputs, put it all in caps, split it into words, join the first character of each word together, and print it. I feel like there should be a loop somewhere, but I'm not entirely sure if that's right or where to put it.
Say input is "Federal Bureau of Agencies"
Typing third[0] gives you the first element of the split, which is "Federal". You want the first element of each element in the sprit. Use a generator comprehension or list comprehension to apply [0] to each item in the list:
val = input("What would you like to acronymize? ")
print("".join(word[0] for word in val.upper().split()))
In Python, it would not be idiomatic to use an explicit loop here. Generator comprehensions are shorter and easier to read, and do not require the use of an explicit accumulator variable.
When you run the code third[0], Python will index the variable third and give you the first part of it.
The results of .split() are a list of strings. Thus, third[0] is a single string, the first word (all capitalized).
You need some sort of loop to get the first letter of each word, or else you could do something with regular expressions. I'd suggest the loop.
Try this:
fourth = "".join(word[0] for word in third)
There is a little for loop inside the call to .join(). Python calls this a "generator expression". The variable word will be set to each word from third, in turn, and then word[0] gets you the char you want.
works for me this way:
>>> a = "What would you like to acronymize?"
>>> a.split()
['What', 'would', 'you', 'like', 'to', 'acronymize?']
>>> ''.join([i[0] for i in a.split()]).upper()
'WWYLTA'
>>>
One intuitive approach would be:
get the sentence using input (or raw_input in python 2)
split the sentence into a list of words
get the first letter of each word
join the letters with a space string
Here is the code:
sentence = raw_input('What would you like to acronymize?: ')
words = sentence.split() #split the sentece into words
just_first_letters = [] #a list containing just the first letter of each word
#traverse the list of words, adding the first letter of
#each word into just_first_letters
for word in words:
just_first_letters.append(word[0])
result = " ".join(just_first_letters) #join the list of first letters
print result
#acronym2.py
#illustrating how to design an acronymn
import string
def main():
sent=raw_input("Enter the sentence: ")#take input sentence with spaces
for i in string.split(string.capwords(sent)):#split the string so each word
#becomes
#a string
print string.join(i[0]), #loop through the split
#string(s) and
#concatenate the first letter
#of each of the
#split string to get your
#acronym
main()
name = input("Enter uppercase with lowercase name")
print(f'the original string = ' + name)
def uppercase(name):
res = [char for char in name if char.isupper()]
print("The uppercase characters in string are : " + "".join(res))
uppercase(name)