I cannot understand why the below code is not updating/incrementing the "spaces" or "sentences" variable - but it is recognising "letters"
Any suggestions would be immense! Thank you so much!!
from cs50 import get_string
text = get_string("text: ")
i = 0
letters = 0
spaces = 0
sentences = 0;
for element in text:
if text[i] != '.' and text[i] != '?' and text[i] != '!' and text[i] != '"' and text[i] != ',' and text[i] != '-' and text[i] != ':' and text[i] != ';' and text[i] != ' ':
letters += 1
for element in text:
if text[i] == " ":
spaces += 1
for element in text:
if text[i] == '.' or text[i] == '?' or text[i] == '!':
sentences += 1
words = spaces +1
L = float(letters/words *100)
S = float(sentences/words *100)
A = float(0.0588*L)
B = float(A - 0.296*S)
C = float(B - 15.8)
index = int(C)
if index < 1:
print("Before Grade 1")
elif index >= 16:
print("Grade 16+")
else:
print("Grade %i\n", index)
print(L,S,A,B,C,index, i, letters, spaces, sentences)
Related
I have a school project question (for Python) that goes like this:
Given a string_input such as "abcd&1-4efg", the function must remove the "&1-4" and insert the string slice from 1 to 4 where the "&1-4" was.
eg. if string_input = "abcd&1-4efg",
"&1-4" is removed.
The remaining characters are indexed as follows: a=0, b=1, c=2, d=3, e=4, f=5, g=6
The new string becomes:
"abcdbcdeefg"
I've managed to write a long chunk of code to do this, but I'm wondering if anyone has any more efficient solutions?
Things to note:
The instructions can include double digits (eg. &10-15)
If the index isn't found, the returned string should print "?" for every missing index
(eg. "abcd&5-10efgh" would return "abcdfgh???efgh")
Intructions can be back-to-back (eg. "&10-15abcdef&1-5&4-5pqrs")
The code I've written is:
def expand(text):
text += "|"
import string
digits_dash = string.digits + "-"
idx_ref_str = ""
replace_list = []
record_val = False
output_to_list = []
instruct = ""
and_idx_mark = 0
#builds replace_list & idx_ref_list
for idx in range(len(text)):
if text[idx] == "&" and record_val==True:
output_to_list.append(instruct)
output_to_list.append(and_idx_mark)
replace_list.append(output_to_list)
output_to_list, instruct, inst_idx, and_idx_mark = [],"",0,0
and_idx_mark = idx
continue
elif text[idx] == "&":
record_val = True
and_idx_mark = idx
continue
#executes if currently in instruction part
if record_val == True:
#adds to instruct
if text[idx] in digits_dash:
instruct += text[idx]
#take info, add to replace list
else:
output_to_list.append(instruct)
output_to_list.append(and_idx_mark)
replace_list.append(output_to_list)
output_to_list, instruct, inst_idx, and_idx_mark, record_val = [],"",0,0,False
#executes otherwise
if record_val == False:
idx_ref_str += text[idx]
idx_ref_str = idx_ref_str[:-1]
text = text[:-1]
#converts str to int indexes in replace list[x][2]
for item in replace_list:
start_idx = ""
end_idx = ""
#find start idx
for char in item[0]:
if char in string.digits:
start_idx += char
elif char == "-":
start_idx = int(start_idx)
break
#find end idx
for char in item[0][::-1]:
if char in string.digits:
end_idx = char + end_idx
elif char == "-":
end_idx = int(end_idx)
break
start_end_list = [start_idx,end_idx]
item+=start_end_list
#split text into parts in list
count = 0
text_block = ""
text_block_list = []
idx_replace = 0
for char in text:
if char == "&":
text_block_list.append(text_block)
text_block = ""
count += len(replace_list[idx_replace][0])
idx_replace +=1
elif count > 0:
count -= 1
else:
text_block += char
text_block_list.append(text_block)
#creates output str
output_str = ""
for idx in range(len(text_block_list)-1):
output_str += text_block_list[idx]
#creates to_add var to add to output_str
start_repl = replace_list[idx][1]
end_repl = replace_list[idx][1] + len(replace_list[idx][0])
find_start = replace_list[idx][2]
find_end = replace_list[idx][3]
if end_idx >= len(idx_ref_str):
gap = end_idx + 1 - len(idx_ref_str)
to_add = idx_ref_str[find_start:] + "?" * gap
else:
to_add = idx_ref_str[find_start:find_end+1]
output_str += to_add
output_str += text_block_list[-1]
return output_str
Here's how I would do it. Always open to criticism.
import re
s = 'abcd&1-4efg'
c = re.compile('&[0-9]+-[0-9]+')
if (m := c.search(s)):
a, b = m.span()
left = s[:a]
right = s[b:]
o = [int(x) for x in m.group(0)[1:].split('-')]
mid = (left+right)[o[0]:o[1]+1]
print(left + mid + right)
In my sentence i want :
replace every # by *
skip every ?
if the ascii value of a char is pair so i am transforming into LowerCase + Shift Value ( input user)
if the ascii value of a char is impair so i am transforming into UpperCase + Shift Value ( input user)
Its tell me
line 19, in replace
new = ord(lower(c)) + (shift % 26)
TypeError: ord() expected string of length 1, but NoneType found
def lower(c):
if 'A' <= c <= 'Z':
c = chr(ord(c) + (ord('a') - ord('A')))
def upper(c):
if 'a' <= 'c' <= 'z':
c = chr(ord(c) - (ord('a') - ord('A')))
def replace(text):
new_text = ''
for c in text:
if c == '#':
new_text += '*'
elif c == '?':
continue
elif ord(c) % 2 == 0:
new = ord(lower(c)) + (shift % 26)
if new > ord('z'):
new = (ord('a') + (new - ord('z')))
new_text += chr(new)
elif ord(c) % 2 != 0:
new = ord(upper(c)) + (shift % 26)
if new_text > 'Z':
new_text = chr('Z' + (new_text - 'Z'))
new_text += chr(new)
return new_text
sentence = (input("Please enter a sentence to encrypt:\n"))
shift = int(input("Please enter the size of the shift:\n"))
sentence = replace(sentence)
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)
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
I need a program that asks the user to enter any text and then display three strings, the first of which consists of all the vowels from the text, the second, of all consonants, and the third, of all other characters. I have it in a while loop right now, I was wondering how I can transfer that into a for-loop in Python.
text = input("Enter text: ")
# Loop counter
i = 0
# Accumulators
vows_string = ""
cons_string = ""
other_str = ""
while i < len(text):
char = text[i]
if char in "aioueAIOUE":
vows_string += char
elif char.isalpha():
cons_string += char
else:
other_str += char
i += 1
# Add pseudo-guillemets to make spaces "visible"
print(">>" + vows_string + "<<")
print(">>" + cons_string + "<<")
print(">>" + other_str + "<<")
Since strings are iterable, you can replace
while i < len(text):
char = text[i]
with
for char in text:
# no more need for 'i'
By the way, try if char.lower() in "aioue":
Now that the code is simple, let's make it potentially more efficient by using a set() for the vowels instead of a string:
# Vowels Set
vowels = set("aeiouAEIOU")
# Accumulators
vowels_string = ""
consonants_string = ""
other_string = ""
# User Input
text = input("Enter text: ")
# Process Text
for char in text:
if char.isalpha():
if char in vowels:
vowels_string += char
else:
consonants_string += char
else:
other_string += char
# Add pseudo-guillemets to make spaces "visible"
print("<<", vowels_string, ">>", sep="")
print("<<", consonants_string, ">>", sep="")
print("<<", other_string, ">>", sep="")