Issue with using append in small program - python

I wanted to test append in my small program. Unfortunately, if does the wrong thing.
Input format
A non-empty text in English, ending with a dot, is supplied to the input of the program (there are no other dot characters in the text).
Output format:
The original line and number on the new line is the number of letters 's' in a line.
init = input()
sentence = []
ses = 0
for i in range(len(init)):
if init[i] == '.':
break
elif init[i] == 's':
ses += 1
elif init[i] != '.' or init[i] == 's':
sentence.append(init[i])
print(''.join(sentence))
print(ses)
Input:
It is not a simple task. Yes!
Expected output:
It is not a simple task
3
But it does:
It i not a imple tak
3

You're forgetting to append the s's and full stops.
init = input()
sentence = []
ses = 0
for i in range(len(init)):
if init[i] == '.':
sentence.append(init[i])
break
elif init[i] == 's':
ses += 1
sentence.append(init[i])
elif init[i] != '.' or init[i] == 's':
sentence.append(init[i])
print(''.join(sentence))
print(ses)
the above should work perfectly

init = input()
Let's say the user typed:
init = 'something is sad.'
Then:
init = init.upper()
list_of_s = []
for letter in init:
if letter == "S":
list_of_s.append(letter)
print(init + str(len(list_of_s)))
First you should transform the input string all to upper letters to normalize the string (you could also user the method .lower()).
Then you define the variable list_of_s where you will store each s matched using append as you requested.
With Python you can iterate a string as if it was a list, each letter we check if it's equal to "S" and if it is we add one s to our list variable.
Finally we use len() to calculate the number of s in our list and print the desired output (we must first transform the number to a string using str()).

Related

SNHU Python 'Simon Says': compare two strings for equality character-wise, without using an index?

I was given a prompt to solve and was able to write code that passed, but my question is, is there a more simplified way I could write this without having to create a new named variable (s_index = 0)? The code works just fine but I'm not sure if I solved it the way I was expected to and am open to suggestions for improvement :)
Please note that this section in the work book has us focusing on using continue and break within loops
"Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G, B, Y)
and the user must repeat the sequence. Create a for loop that compares the two strings.
For each match, add one point to user_score. Upon a mismatch, end the game.
Sample output with inputs: 'RRGBRYYBGY' 'RRGBBRYBGY'
User score: 4
user_score = 0
simon_pattern = input()
user_pattern = input()
s_index = 0
for letter in user_pattern:
if letter == simon_pattern[s_index]:
user_score += 1
s_index += 1
else:
break
print('User score:', user_score)
using functions to encapsulate small specific parts of your logic is often helpful
def do_score(user_pattern="1234",simon_pattern="1235"):
# using enumerate you can get the indices
for s_index,a_char in enumerate(simon_pattern):
if s_index >= len(user_pattern) or a_char != user_pattern[s_index]:
# the index should always match the "sum" so no need to track or compute the sum
return s_index
return len(simon_pattern)
this method takes 2 strings and "scores" them based on the "simon_pattern" returning the score
then just
print(do_score(user_entered_input,simon_pattern))
I will rewrite this to this way: (this way you can completely eliminate the variable index, and simon_pattern[index] to get the letter)
Note - in Python a word is just a sequence of character/letters, you can iterate it directly, no need to use index.
simon = 'RRGBRYYBGY'
user = 'RRGBBRYBGY' # User score: 4
user_score = 0
for user_char, simon_char in zip(user, simon):
if user_char == simon_char: # continue to check/and match...
user_score += 1
else: # break, if no match!
break
print('User score:', user_score)
Strictly, you never need to know the index or index into the strings, you can just use zip() to combine tuples of respective characters from the two (possibly different-length) strings:
def do_score(user_pattern='RRGBRYYBGY', simon_pattern='RRGBBRYBGY'):
score = 0
for uc,sc in zip(user_pattern, simon_pattern):
if uc == sc:
score += 1
else:
break
return score
assert do_score('', '') == 0
assert do_score('RRG', '') == 0
assert do_score('', 'RRG') == 0
assert do_score('RRG', 'RRGB') == 3

How to select certain characters in a string in Python?

My name is Shaun. I am 13 years old and trying to learn python.
I am trying to make a program that finds vowels in an input and then prints how many vowels there are in the input the user gives.
Here is the code:
s = (input('Enter a string: ')) # Let the user give an input (has to be a string)
Vwl = [] # Create an array where we will append the values when the program finds a vowel or several vowels
for i in s: # Create a loop to check for each letter in s
count_a = 0 # Create a variable to count how many vowels in a
count_e = 0 # Create a variable to count how many vowels in e
count_i = 0 # Create a variable to count how many vowels in i
count_o = 0 # Create a variable to count how many vowels in o
count_u = 0 # Create a variable to count how many vowels in u
The function below is pretty long to explain, so summary of the function below is to find a vowel in s (the input) and make one of the counters, if not some or all, increase by 1. For the sake of learning, we append the vowels in the array Vwl. Then, it prints out Vwl and how many letters there are in the list by using len.
if s.find("a" or "A") != -1:
count_a = count_a + 1
Vwl.append('a')
elif s.find("e" or "E") != -1:
count_e = count_e + 1
Vwl.append("e")
elif s.find("i" or "I") != -1:
count_i = count_i + 1
Vwl.append("i")
elif s.find("o" or "O") != -1:
count_o = count_o + 1
Vwl.append("o")
elif s.find("u" or "U") != -1:
count_u = count_u + 1
Vwl.append("u")
print(Vwl)
print(f"How many vowels in the sentence: {len(Vwl)}")
For some odd reason however, my program first finds the first vowel it sees, and converts the whole string into the first vowel it finds. Then it prints down the wrong amount of vowels based on the array of vowels in the array Vwls
Could someone please help me?
The reason your code only prints out the first vowel is because the if statements you coded are not inside a loop, that part of the code runs once and then it finishes, so it only manages to find one vowel.
Here are couple ways you can do what you are trying to do:
Way 1: Here is if you just want to count the vowels:
s = input()
vowel_counter = 0
for letter in s:
if letter in "aeiou":
vowel_counter+=1
print(f"How many vowels in the sentence: {vowel_counter}")
Way 2: Use a python dictionary to keep track of how many of each vowel you have
s = input()
vowel_dict = {}
for letter in s:
if letter in "aeiou":
if letter not in vowel_dict:
vowel_dict[letter]=0
vowel_dict[letter]+=1
print(f"How many vowels in the sentence: {sum(vowel_dict.values())}")
print(vowel_dict)

While loop using strings and if statements

Prompt for python program:
5.16 LAB: Password modifier
Many user-created passwords are simple and easy to guess. Write a program that takes a simple password and makes it stronger by replacing characters using the key below, and by appending "!" to the end of the input string.
i becomes 1
a becomes #
m becomes M
B becomes 8
s becomes $
Ex: If the input is:
mypassword
the output is:
Myp#$$word!
Hint: Python strings are immutable, but support string concatenation. Store and build the stronger password in the given password variable.
My code so far:
word = input()
password = ''
i = 0
while i < len(word):
I'm really just confused about changing certain characters in a string using a while loop. I was also trying to use if statements. While loops are hard for me understand. I don't know where to start.
You're doing fine. While loops have this format:
while (condition) == True:
# do this
In your case, you will want to put i += 1 at then end of your loop so it doesn't go on forever, like this:
while i < len(word):
# your code here
i += 1 # this adds 1 to i
# so eventually it will be equal to the length of word, ending the loop
As for if statements, you could try this:
while i < len(word):
if word[i] == 'i':
password += '1'
i += 1
The if statements will only work on the values you want to change, so add an else statement to act as a default.
while i < len(word):
if word[i] == 'i':
password += '1'
else:
password += word[i]
i += 1
Now, if you get a normal letter, like h, it will add it to the password.
Hope this helps you get started!

Running code isn't providing any output

I have a program that, simplified, looks like this:
def listAssign(lst,index,item):
"""Assigns item item to list lst at index index, returns modified list."""
lst[index] = item
return lst
def listInsert(lst,index,item):
"""Inserts item item to list lst at index index, returns modified list."""
lst.insert(index.item)
return lst
# ...
def listSurgery(lst,indices,f,*extraArgs):
"""Performs operation f on list lst at depth at indices indices, returns modified list."""
parent = lst
for index in indices[:-1]:
parent = parent[index]
parent = f(parent,indices[-1],*extraArgs)
return listSurgery(lst,indices[:-1],listAssign,parent)
# ...
def parseStringToList(s):
"""Takes in a user-input string, and converts it into a list to be passed into parseListToExpr."""
for c in s[:]: # Removes extra spaces from beginning of string
if c == ' ':
s = s[1:]
else:
break
for c in s[::-1]: # Removes spaces from end of string
if c == ' ':
s = s[:-1]
else:
break
l = [] # List to build from string; built by serially appending stuff as it comes up
b = True # Bool for whether the parser is experiencing spaces (supposed to be True if last character processed was a space)
t = False # Bool for whether the parser is experiencing a string of non-alphanumeric characters (supposed to be True if last character was a non-alphanumeric character)
lvl = 0 # Keeps track of depth at which operations are supposed to be occurring
for c in s:
if c == ' ': # If the character is a space, do nothing, but make sure that it's documented that the last character processed was a space
b = True
elif c == '(' or c == '[': # If the character is an opening parenthesis, add a new level of depth to the list, by appending another list to the lowest level and incrementing lvl
l = listSurgery(l,[-1]*(lvl+1),listInsert,[])
lvl += 1
if c == '[': # ] (left here for overzealous parsers) If the bracket is square, also append a comma as the first element of the appended list
l = listSurgery(l,[-1]*(lvl+1),listInsert,',')
elif c == ')' or c == ']': # If it's a closing parenthesis, make it stop paying attention to the list it's working on
lvl -= 1
elif c == ',': # If it's a comma, then append it to the list as a separate element and start a new string to append characters to
l = listSurgery(l,[-1]*(lvl+1),lambda x,y,z:listAssign(x,y,x[y]+z),[',',''])
elif not c.alnum(): # If it's non-alphanumeric and not any of the above, then append it to string that it's working on if it's a non-alphanumeric string
if not t: # If the string that it's working on isn't non-alphanumeric, then finish working on that string and append a new string to work on
l = listSurgery(l,[-1]*(lvl+1),listInsert,'')
l = listSurgery(l,[-1]*(lvl+1),lambda x,y,z:listAssign(x,y,x[y]+z),c)
t = True
else: # If the character is alphanumeric, append it to the string it's working on
assert c.isalnum()
if b or t: # If the string it's working on isn't alphanumeric or doesn't exist, append a new string
l = listSurgery(l,[-1]*(lvl+1),listInsert,'')
b, t = False, False
l = listSurgery(l,[-1]*(lvl+1),lambda x,y,z:listAssign(x,y,x[y]+z),c)
return l
# ...
cmds = {
'help':"List the available functions.",
'quit':"Quit this application.",
'exit':"Exit this application (exactly the same thing)."
}
print "MAT (Michael's Analysis Tool), version 0.0.0"
op = '' # Declare string to use for input
while op != 'exit' and op != 'quit': # Keep a REPL unless the user types "exit" or "quit", in which case exit
op = raw_input("> ")
if op == 'help':
print "The commands available in addition to free evaluation are:"
for item in cmds:
print ' ', item + ":", cmds[item]
elif op == 'quit' or 'exit':
pass
else:
print str(parseStringToList(op))
When I use help, quit, or exit as a command, it comes out fine. But when I give it any other kind of input like 1 + 1 = 2 (which should elicit ['1','+','1','=','2']) or This is a sentence. (which should elicit ['This','is','a','sentence','.'], it doesn't print anything, just asks for more input. (That is, it's functionally equivalent to the last line of this program getting replaced with continue.) And I don't understand why. parseStringToList is defined in a very straightforward manner. It should at least return [], the original value of the variable it returns. But instead it doesn't print anything. Why? (I'll try more thorough debugging tomorrow, but so far it's eluded my efforts.)
You need to change this:
elif op == 'quit' or 'exit':
to this
elif op == 'quit' or op == 'exit':

why am i getting an error for my cipher function (python)?

here's my code:
def encode(pattern, filename):
pattern = ['a','e','s','3']
message = open(filename, 'r+')
for letter in message:
if letter == pattern[0]:
letter == pattern[1]
elif letter == pattern[1]:
letter == pattern[0]
elif letter == pattern[2]:
letter == pattern[3]
else:
continue
message.close()
probably a few flaws in the code as I'm only an amateur at python, but when i run the function, the file remains unchanged. what am i doing wrong?
there is a difference between == and =. == is used to test if two objects or primitives are the same, = is used to assign values to objects or primitives.
try making these changes:
for letter in message:
if letter == pattern[0]:
letter = pattern[1] ## <-- change
elif letter == pattern[1]:
letter = pattern[0] ## <-- change
elif letter == pattern[2]:
letter = pattern[3] ## <-- change
else:
continue
but this just assigns a value to letter which will be changed the next iteration through the loop, what you really want to do is write to some other file, or write back to message (but this could be dangerous since you are reading from it).
I. Unless I'm mistaken, you're not actually editing the file, even with the r+ mode, by making assignments to letter. You still need to use write to actually make changes to the file.
II. You may be interested in string.translate:
In [112]: t = string.maketrans('abc', 'bad')
In [115]: s = 'abcdef'
In [116]: s.translate(t)
Out[116]: 'baddef'

Categories