Counting the number of capital letters in an input?- in python - python-3.x

On python how do you make a program that asks for an input and the program works out the number of capital letters in that input and output the number of capital letters?

Loop through the string and use .isupper() to check if the letter is uppercase and increment the count. Finally print the count.
inpt = raw_input('Enter something: ')
c = 0
for i in inpt:
if i.isupper():
c += 1
print "No. of uppercase letters: ", c

len(filter(lambda x:isupper(x),list(input("Enter String"))))

Try the following function:
def capital(word):
num = 0
for char in word:
if char.isupper():
num+=1
return num
And incorporate it as such:
word = input('Enter: ')
print capital(word)

Related

Python add spaces between letters but not between other characters?

I'm looking to have a function that adds spaces in between letters, but doesn't add any spaces between other characters (for example not between a "2" and a letter, or between a letter and an apostrophe). The input strings already have spaces after any non-letter character.
For example, given the string "RU2 FLB' L2 r2 fB'", the output would be "R U2 F L B' L2 r2 f B'".
Thanks for any help :)
you can use this code, very simple and understandable, you can change it to a function or use by lambda and so on...
my_string = "RU2 FLB' L2 r2 fB" #or any input
output = '' #your output
num = ['1','2','3','4','5','6','7','8','9','0','\''] #you can add any other symbols may use in your string
for i in range(len(my_string)):
if my_string[i] == ' ':
continue
elif i < (len(my_string) -1) and num.count(my_string[i+1]) > 0:
output = output + my_string[i]
continue
elif my_string[i]:
output = output + my_string[i] + ' '
print(output)

hello friends i cant execute my else condition

The program must accept a string S as the input. The program must replace every vowel in the string S by the next consonant (alphabetical order) and replace every consonant in the string S by the next vowel (alphabetical order). Finally, the program must print the modified string as the output.
s=input()
z=[let for let in s]
alpa="abcdefghijklmnopqrstuvwxyz"
a=[let for let in alpa]
v="aeiou"
vow=[let for let in v]
for let in z:
if(let=="a"or let=="e" or let=="i" or let=="o" or let=="u"):
index=a.index(let)+1
if index!="a"or index!="e"or index!="i"or index!="o"or index!="u":
print(a[index],end="")
else:
for let in alpa:
ind=alpa.index(let)
i=ind+1
if(i=="a"or i=="e" or i=="i"or i=="o"or i=="u"):
print(i,end="")
the output is :
i/p orange
pbf
the required output is:
i/p orange
puboif
I would do it like this:
import string
def dumb_encrypt(text, vowels='aeiou'):
result = ''
for char in text:
i = string.ascii_letters.index(char)
if char.lower() in vowels:
result += string.ascii_letters[(i + 1) % len(string.ascii_letters)]
else:
c = 'a'
for c in vowels:
if string.ascii_letters.index(c) > i:
break
result += c
return result
print(dumb_encrypt('orange'))
# puboif
Basically, I would use string.ascii_letters, instead of defining that anew. Also, I would not convert all to list as it is not necessary for looping through. The consonants you got right. The vowels, I would just do an uncertain search for the next valid consonant. If the search, fails it sticks back to default a value.
Here I use groupby to split the alphabet into runs of vowels and consonants. I then create a mapping of letters to the next letter of the other type (ignoring the final consonants in the alphabet). I then use str.maketrans to build a translation table I can pass to str.translate to convert the string.
from itertools import groupby
from string import ascii_lowercase as letters
vowels = "aeiou"
is_vowel = vowels.__contains__
partitions = [list(g) for k, g in groupby(letters, is_vowel)]
mapping = {}
for curr_letters, next_letters in zip(partitions, partitions[1:]):
for letter in curr_letters:
mapping[letter] = next_letters[0]
table = str.maketrans(mapping)
"orange".translate(table)
# 'puboif'

Lexicographically smallest palindrome in python

I found this question to be interesting and I would like to share this here and find reasonably good codes, specific to py :
Given a string S having characters from English alphabets ['a' - 'z'] and '.' as the special character (without quotes).
Write a program to construct the lexicographically smallest palindrome by filling each of the faded character ('.') with a lower case alphabet.
Definition:
The smallest lexicographical order is an order relation where string s is smaller than t, given the first character of s (s1 ) is smaller than the first character of t (t1 ), or in case they
are equivalent, the second character, etc.
For example : "aaabbb" is smaller than "aaac" because although the first three characters
are equal, the fourth character b is smaller than the fourth character c.
Input Format:
String S
Output Format:
Print lexicographically smallest palindrome after filling each '.' character, if it
possible to construct one. Print -1 otherwise.
Example-1
Input:
a.ba
Output:
abba
Example-2:
Input:
a.b
Output:
-1
Explanation:
In example 1, you can create a palindrome by filling the '.' character by 'b'.
In example 2, it is not possible to make the string s a palindrome.
You can't just copy paste questions from NPTEL assignments and ask them here without even trying!
Anyways,since the "code" is your only concern,try copy pasting the lines below:
word = input()
length = len(word)
def SmallestPalindrome(word, length):
i = 0
j = length - 1
word = list(word) #creating a list from the input word
while (i <= j):
if (word[i] == word[j] == '.'):
word[i] = word[j] = 'a'
elif word[i] != word[j]:
if (word[i] == '.'):
word[i] = word[j]
elif (word[j] == '.'):
word[j] = word[i]
else: # worst case situation when palindrome condition is not met
return -1
i = i + 1
j = j - 1
return "".join(word) # to turn the list back to a string
print(SmallestPalindrome(word, length)) #Print the output of your function
s=input()
s=list(s)
n=len(s)
j=n
c=0
for i in range(n):
j=j-1
if((s[i]==s[j]) and (i==j) and (s[i]=='.' and s[j]=='.')):
s[i]='a'
s[j]='a'
elif(s[i]==s[j]):
continue
elif((s[i]!=s[j]) and (i!=j) and (s[i]=='.' or s[j]=='.')):
if(s[i]!='.'):
s[j]=s[i]
else:
s[i]=s[j]
elif((i==j) and (s[i]=='.')):
s[i]=a
else:
c=c+1
break
if(c<1):
for k in s:
print(k,end="")
else:print("-1")

How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string

def shortenPlus(s) -> "s without some vowels":
for char in s:
if char in "AEIOUaeiou":
return(s.replace(char,""))
I have the taken it out of the entire string. But I can't figure out how to restrict the replace function to everything but the first letter of each word in a string.
Not sure exactly what you're looking for, can you clarify, perhaps give a simple example? None of the words you have in your example start with vowels!
But here you could remove all the vowels in a word except the first vowel of the first word. Hard coded but gives you an idea:
s="without some vowels"
for char in s[2:]:
if char in "AEIOUaeiou":
s=s.replace(char,"")
print(s)
Outputs
witht sm vwls
Alternatively, to get the first char of every word, you could use a sentinel value that flags each time a non-alpha char such as punctuation or a space is present, then keeps the next char but not the others.
s="without some vowels"
sent=2
for char in s:
if sent>0:
sent-=1
print(char)
continue
if not char.isalpha():
sent=2
continue
s=s.replace(char,"")
print(output)
Outputs
w s v
def shortenPlus(s):
counter = 0 # accepted character count
add_the_vowel = True # check if vowel came for the first time for the word
temp = " " # temp string to store the output
for letter in s:
if letter == " ":
add_the_vowel= True
if add_the_vowel == True and letter in "AEIOUaeiou":
temp += s[counter] # first vowel of the word
if letter in "AEIOUaeiou":
add_the_vowel = False # restrict second vowel appeared
else:
temp += s[counter]
counter += 1
print(temp)
s = "without some vowels frienis"
shortenPlus(s)
How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string
output :
witht som vowls frins

What is going wrong in my hangman program?

I'm trying to get a function to put correct guesses in their blanks in a hangman program, but all it does is, whatever the guess and no matter whether it's right or wrong, it just gradually reveals the word. Where am I going wrong?
code:
while lettersrevealed!=word:
guess=getGuess(lettersrevealed)
for i in range(len(word)):
if guess in word:
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
ex:
(secret word is badger)
Guess a letter:
a
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
OR:
Guess a letter:
h
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
The issue is with the for loop
for i in range(len(word)): # This will run 6 times for "badger" | 0, 1, .., 5
if guess in word:
# blanks == ****** then gradually gets the next letter added replacing a *
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
You probably want something like this.
def convert_to_blanks(word, letters):
return ''.join(c if c in letters else '*' for c in word)
>>> word = 'badger'
>>> letters = set()
>>> convert_to_blanks(word, letters)
'******'
>>> letters.add('g')
>>> letters
{'g'}
>>> convert_to_blanks(word, letters)
'***g**'
And so you have a while loop prompting for letter something like this.
guessed = set()
word = 'badger'
while True:
guess = input("Guess a letter")
guessed.add(guess)
blanks = convert_to_blanks(word, guessed)
print(blanks)
if blanks == word:
break

Resources