How can I make this code shorter (less lines etc) - python

I am writing a code and want to make it as short as possible, is there any way i can?
text = raw_input("Give me some text > ")
list1 = []
for char in text:
num = ord(char)
if num in range(48,57):
print "ERROR 319: Number entered"
quit()
elif num in range(65,90) or num in range (97,122):
upper = char.upper()
list1.append(upper)
num1 = 0
vowelCount = 0
conCount = 0
for x in range(len(list1)):
if list1[num1] == "A" or list1[num1] == "E" or list1[num1] == "I" or list1[num1] == "O" or list1[num1] == "U":
vowelCount = vowelCount + 1
else:
conCount = conCount + 1
num1 = num1 + 1
print "Vowels: " +str(vowelCount) + " Consonants: " + str(conCount)

Instead of taking ord() of the character, you can use the string methods:
char.isdigit() # check if a char is a digit
char.isalpha() # check if char is letter
For checking the vowel counts, try:
vowel_count = len(filter(lambda c: c in "aeiou", list1))
cons_count = len(list1) - vowel_count

Building off of AmourK's answer, you could do something like this:
text = raw_input("Give me some text > ")
vowel_count = len(filter(lambda c: c in "aeiou", text))
cons_count = len(filter(lambda c: c not in "aeiou" and c.isalpha(), text))
print "Vowels: %d Consonants: %d" % (vowel_count, cons_count)

Related

Swap upper and lower case with its ASCII value

Im trying to swap letter type with its ASCII value however I am only getting the last word of the string as an output. it also will not accept any string with number values
def get_sentence():
sentence = input("Please input the sentence:")
words = sentence.split(' ')
sentence = ' '.join(reversed(words))
return sentence
ans = ''
def main():
sentence = get_sentence()
ans =''
for s in sentence:
if ord(s) >= 97 and ord(s) <= 122:
ans = ans + chr(ord(s) - 32)
elif ord(s) >= 65 and ord(s) <= 90 :
ans = ans + chr(ord(s) + 32)
else :
ans += ' '
print(ans)
if __name__ == "__main__":
main()
I am not sure if this is the result you want (adding expected output would be helpful next time) but removing the print statement outside the for loop seems to fix it for me.
def get_sentence():
sentence = input("Please input the sentence:")
words = sentence.split(' ')
sentence = ' '.join(reversed(words))
return sentence
ans = ''
def main():
sentence = get_sentence()
ans =''
for s in sentence:
if ord(s) >= 97 and ord(s) <= 122:
ans = ans + chr(ord(s) - 32)
elif ord(s) >= 65 and ord(s) <= 90 :
ans = ans + chr(ord(s) + 32)
else :
ans += ' '
print(ans) # this should be outside!
if __name__ == "__main__":
main()
There's a simpler way to do this, using built-in methods isupper() and islower(). Then you don't need to handle sentences (or punctuation) separately.
def swap_case(sentence: str) -> str:
letters = (
letter.upper() if letter.islower() else letter.lower()
for letter in sentence
)
return "".join(letters)
print(swap_case(get_sentence()))
Notice my function also returns the result rather than printing it. And it takes input of the sentence, so you can use it in other cases, which makes it more reusable. Not sure why you want the words of the sentence reversed... but ¯\_(ツ)_/¯

Python strings formatting

Given a string containing at least one space character.
Output the substring located between the first and second spaces of the source string. If the string contains only one space, then output an empty string.
My attempt:
But input is incorrect, for example: user_input=Hello World my name , input is: World my , i don't know why , can you help me?
user_input = input("Enter your string: ")
space_counter = 0
for char in user_input:
if char == " ":
space_counter += 1
if space_counter > 1:
start_space_index = None
for i in range(len(user_input)):
if user_input[i] == " ":
start_space_index = i
break
second_space_index = None
for i in range(len(user_input)-1, -1, -1):
if user_input[i] == " ":
second_space_index = i
break
print(user_input[start_space_index+1: second_space_index])
else:
print("Empty string")
Example: 1
Assuming the input like:
hello my name is abc
Output should be
hello my
Example 2:
input
hello my
output
None
Code:
a = 'hello my name is abc'
obj = a.split(" ") #this splits like ['hello', 'my', 'name', 'is', 'abc']
if len(obj) > 2:
print(obj[0], obj[1])
else:
print None
Here, it is
user_input = input("Enter your string: ")
Lst = user_input.split(" ")
space_counter = 0
for char in user_input:
if char == " ":
space_counter += 1
if space_counter > 1:
start_space_index = None
for i in range(len(user_input)):
if user_input[i] == " ":
start_space_index = i
break
second_space_index = None
for i in range(len(user_input)-1, -1, -1):
if user_input[i] == " ":
second_space_index = i
break
if user_input[0] == " ":
print(Lst[0])
else:
print(Lst[1])

IndexError: String Index out of range for recursive function

So I am learning python and am trying to count the number of vowels in a sentence. I figured out how to do it both using the count() function and an iteration but now I am trying to do it using recursion. When I try the following method I get an error "IndexError: string index out of range". Here is my code.
sentence = input(": ")
def count_vowels_recursive(sentence):
total = 0
if sentence[0] == "a" or sentence[0] == "e" or sentence[0] == "i" or sentence[0] == "o" or sentence[0] == "u":
total = total + 1 + count_vowels_recursive(sentence[1:])
else:
total = total + count_vowels_recursive(sentence[1:])
return the_sum
print(count_vowels_recursive(sentence))
Here are my previous two solutions.
def count_vowels(sentence):
a = sentence.count("a")
b = sentence.count("e")
c = sentence.count("i")
d = sentence.count("o")
e = sentence.count("i")
return (a+b+c+d+e)
def count_vowels_iterative(sentence):
a_ = 0
e_ = 0
i_ = 0
o_ = 0
u_ = 0
for i in range(len(sentence)):
if "a" == sentence[i]:
a_ = a_ + 1
elif "e" == sentence[i]:
e_ = e_ + 1
elif "i" == sentence[i]:
i_ = i_ + 1
elif "o" == sentence[i]:
o_ = o_ + 1
elif "u" == sentence[i]:
u_ = u_ + 1
else:
continue
return (a_ + e_ + i_ + o_ + u_)
You have no base case. The function will keep recursing until sentence is empty, in which case your first if statement will cause that index error.
You should first of all check if sentence is empty, and if so return 0
You can shorten things up quite a bit:
def count_vowels_recursive(sentence):
# this base case is needed to stop the recursion
if not sentence:
return 0
# otherwise, sentence[0] will raise an exception for the empty string
return (sentence[0] in "aeiou") + count_vowels_recursive(sentence[1:])
# the boolean expression `sentence[0] in "aeiou"` is cast to an int for the addition
You can try this:
def count_vowels_recursive(s, count):
if not s:
return count
else:
new_count = count
if s[0] in ["a", "e", "i", "o", "u"]:
new_count += 1
return count_vowels_recursive(s[1:], new_count)

python caesar chr and ord without newline and just iterate in the alphabet

I have some problem with my caesar code.
1) I don't know how to check if a character is a punctuation and print without sum.
2) print the char on the same line but when it's finished return a newline.
3) Iterate through the alphabet with big number return me a punctuation, how can I do to return just a character?
import sys
import string
def main():
if len(sys.argv) != 2:
print("Usage: caesar.py k")
else:
k = int(sys.argv[1])
if k == 1 or k <= 26:
text = input("plaintext: ");
j = len(text)
for i in range(j):
#check if is a character
if text[i].isalpha:
if text[i].islower():
print(chr(ord(text[i]) + k),end = "")
if text[i].isupper():
print(chr(ord(text[i]) + k),end = "")
elif text[i].punctuation():
print(text[i])
else:
print("You have to introduce a number between 1 and 26")
main()
Try this code:
import string
def encrypt_ceasar(s, shift):
assert abs(shift) < 26, 'shift is between -25 and 25 (inclusive)'
encrypted_s = ''
for char in s:
if char.isalpha():
is_upper = char.isupper()
char = char.lower()
pos_alphabet = ord(char) - ord('a')
new_pos = (pos_alphabet + shift) % 26
encryted_char = chr(ord('a') + new_pos)
if is_upper:
encryted_char = encryted_char.upper()
encrypted_s += encryted_char
else:
encrypted_s += char
return encrypted_s
def decrypt_ceasar(s, shift):
return encrypt_ceasar(s, -shift)
if __name__ == "__main__":
s = 'AbC1$de#zy'
encrypted_s = encrypt_ceasar(s, 3)
print('s:', s)
print('encrypted_s:', encrypted_s)
print('again s:', decrypt_ceasar(encrypted_s, 3))
Output:
s: AbC1$de#zy
encrypted_s: DeF1$gh#cb
again s: AbC1$de#zy

Translating sentences into pig latin

SO i have this assignment to translate multiple words into pig latin. assume that the user will always input lowercase and only letters and spaces.
#----------------global variables
sentence = input("What do you want to translate into piglattin? ")
sentence = list(sentence)
sentence.insert(0, ' ')
length = len(sentence)
sentence.append(' ')
pigLattin = sentence
false = 0
true = 1
consonant = []
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
j = 0
x = 0
y = 0
#----------------main functions
def testSpace(sentence, i):
if sentence[i] == ' ':
a = true
else:
a = false
return a
def testVowel(sentence, i):
if sentence[i] == 'a' or sentence[i] == 'e' or sentence[i] == 'i' or sentence[i] == 'o' or sentence[i] == 'u' or sentence[i] == 'y':
b = true
else:
b = false
return b
def testStartWord(sentence, i):
x = 0
if sentence[i].isalpha() and sentence[i-1] == ' ':
c = true
x = 1
if x == 1 and sentence[i] != 'a' and sentence[i] != 'e' and sentence[i] != 'i' and sentence[i] != 'o' and sentence[i] != 'u' and sentence[i] != 'y':
c = true
else:
c = false
return c
def testWordEnd(sentence, i):
if sentence[i].isalpha() and sentence[i+1] == ' ':
d = true
else:
d = false
return d
#----------------main loop
for i in range(1,length):
x = 0
space = testSpace(sentence, i)
vowel = testVowel(sentence, i)
word = testStartWord(sentence, i)
end = testWordEnd(sentence, i)
if vowel == false and space == false and word == true:
e = i
consonant.append(sentence[i])
pigLattin.pop(e)
f = f + 1
if end == true:
consonant.append('a')
consonant.append('y')
consLength = len(consonant)
for x in range(consLength):
y = i + j - f
pigLattin.insert(y,consonant[x])
j = j + 1
del consonant[:]
pigLength = len(pigLattin)
for b in range (pigLength):
print(pigLattin[b], end='')
this is what i have so far. it gets kinda messy when trying to remove items. im sort of stuck here and its not working.
OK i got it working now this is an updated version
sentence = input("Please enter a sentence: ")
vowels = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
words = sentence.split()
count = 0
def find_vowel(word):
for i in range(len(word)):
if word[i] in vowels:
return i
return -1
for word in words:
vowel = find_vowel(word)
if(vowel == -1):
print(word, ' ', end='')
elif(vowel == 0):
print(word + "ay", ' ', end='')
else:
print(word[vowel:] + word[:vowel] + "ay", ' ', end='')
Instead of using testSpace eliminate the spaces by using sentence = sentence.split(). This will split all your words into strings in a list. Then iterate through the words in your list.
Instead of using testStartWord, use an if statement:
for word in sentence:
if word[0] in ["a","e","i","o","u"]:
word[:(len(word)-1)] = word[0]
#More Code...
At the end, where you print the output, use print sentence.join()
Here's an alternate version. I use a regular expression to find words in the input string, pass them to a callback function, and substitute them back into the original string. This allows me to preserve numbers, spacing and punctuation:
import re
import sys
# Python 2/3 compatibility shim
inp = input if sys.hexversion >= 0x3000000 else raw_input
VOWELS = set('aeiouyAEIOUY')
YS = set('yY')
def pig_word(word):
"""
Given a word, convert it to Pig Latin
"""
if hasattr(word, 'group'):
# pull the text out of a regex match object
word = word.group()
# find the first vowel and what it is
vowel, where = None, None
for i,ch in enumerate(word):
if ch in VOWELS:
vowel, where = ch, i
break
if vowel is None:
# No vowels found
return word
elif where == 0 and vowel not in YS:
# Starts with a vowel - end in 'way'
# (leading y is treated as a consonant)
return word + 'way'
else:
# Starts with consonants - move to end and follow with 'ay'
# check capitalization
uppercase = word.isupper() and len(word) > 1
titlecase = word[:1].isupper() and not uppercase
# rearrange word
word = word[where:] + word[:where] + 'ay'
# repair capitalization
if uppercase:
word = word.upper()
elif titlecase:
# don't use str.title() because it screws up words with apostrophes
word = word[:1].upper() + word[1:].lower()
return word
def pig_latin(s, reg=re.compile('[a-z\']+', re.IGNORECASE)):
"""
Translate a sentence into Pig Latin
"""
# find each word in the sentence, pass it to pig_word, and insert the result back into the string
return reg.sub(pig_word, s)
def main():
while True:
s = inp('Enter a sentence to translate (or Enter to quit): ')
if s.strip():
print(pig_latin(s))
print('')
else:
break
if __name__=="__main__":
main()
then
Enter a sentence to translate (or Enter to quit):
>>> Hey, this is really COOL! Let's try it 3 or 4 times...
Eyhay, isthay isway eallyray OOLCAY! Et'slay ytray itway 3 orway 4 imestay...

Categories