I am doing this python problem where I have to get a word input from the user and then flip the word backwards and print the letters out backwards, adding a letter each time. I've made it so I can flip the word backwards. I know I can use the
for c in word
statement but I'm unsure how to make it so I can add a letter each time.
Below are the instructions and my code.
The childrens' song Bingo is from 1780!
In the song, each verse spells the name "Bingo", removing one letter
from the name each time.
When
writing this program, you'll need to work out a few things:
You need a way to reverse the dog's name. You need a loop to build up
the dog's name letter by letter. Each time you go through the loop you
add another letter to the reversed name.
An example:
Name: bingo o
og
ogn
ogni
ognib
And ognib was their name-o
Code I have:
name = input("Name: ")
reversed_text = ''
last_index = len(name) - 1
for i in range(last_index, -1, -1):
reversed_text += name[i]
print(reversed_text)
Thanks
Your answer was pretty much on point, all you needed to do was indent the last line, so it prints out reversed_text each time a letter is added to it.
name = input("Name: ")
reversed_text = ''
last_index = len(name) - 1
for i in range(last_index, -1, -1):
reversed_text += name[i]
print(reversed_text)
Python's reverse list slicing can help you here.
name = input()
for i in range(2,len(name)+2):
print(name[-1:-i:-1])
Output:
o
og
ogn
ogni
ogniB
Here is one way to do what you want. Note that I changed your method of reversing the string--my way used just one line. You may understand the slice method used here, reducing the index by 1 each time using the -1 in the slice.
The printing of the partial names uses a loop, with each iteration printing a slice of the reversed name. Let me know if you have any questions.
name = input("Name: ")
reversed_text = name[::-1]
for i in range(1, len(name) + 1):
print(reversed_text[:i])
print('And', reversed_text, 'was their name-o')
This prints:
o
og
ogn
ogni
ognib
And ognib was their name-o
I am not sure I understand all your requirements but this may be useful to you:
word = 'Bingo'
drow = ''
for c in reversed(word):
drow += c
print drow
Output:
o
og
ogn
ogni
ogniB
Related
I am a beginner and this is what I came up with so far. However, it does not output the correct number of words that end with "a" or "b." Any tips on how to correct this code?
names = input("Enter list of names: ")
name = names.split(" ")
num = len(name)
ab = ""
print("Number of words:", num)
for i in range(num):
if name[i] == ' ':
if name[i-1] == a:
ab.append() + " "
elif name[i-1] == b:
ab.append() + " "
a_b = ab.split(' ')
print("Number of words that end with a or b: ",len(a_b))
In Python boolean (True and False) are the same as the integers 1 and 0. This means you can use sum() to count True booleans. str.endswith() returns a boolean. This means you can just do this:
words = ["stab", "drama", "hello", "magma", "test"]
a_b = sum(word.endswith(('a', 'b')) for word in words)
# 3
z_c = sum(word.endswith(('z', 'c')) for word in words)
# 0
Any tips on how to correct this code?
Others have answered alternative, working solutions, but I want to try to point out the specific things wrong in your code snippet and tips to correct.
First here's a copy of your snippet with some simple debugging prints along with their output (running in python 3.10).
names = "Barry Lima Bab"
name = names.split(" ")
print(f"{name=}") # name=['Barry', 'Lima', 'Bab']
num = len(name)
print(f"{num=}") # num=3
ab = ""
print("Number of words:", num)
for i in range(num):
print(name[i]) # Barry -> Lima -> Bab
if name[i] == ' ':
if name[i-1] == a:
ab.append() + " "
elif name[i-1] == b:
ab.append() + " "
print(f"{ab=}") # ab=''
a_b = ab.split(' ')
print(f"{a_b=}") # a_b=['']
Breaking things down step by step like this is a great starting point for better understanding what's going on.
if name[i] == ' ': Notice the value of name[i] so this check never resolves to True meaning the code inside never runs
if the inner code did run, you'd hit a NameError: name 'a' is not defined. Did you mean: 'ab'? because a is undefined. Probably meant 'a' here. same for b
In my example, name[i-1] would be 'Bab' -> 'Barry' -> 'Lima' which is probably not what you're expecting. This is because you're getting the -1th, 0th, 1st items in name. to get the last letter from the name, you want name[i][-1] here
if you then get into either of the furthest inside conditions, you'd encounter AttributeError: 'str' object has no attribute 'append' which happens because append is for list not str. You couldchange ab to be a list to use this in which case you'd want ab.append(name[i]) or you can use string concatenation like ab += " " + name[i] or using str.concat
1 last note of interest, you may have noticed your code as-is really likes to return and say that there's 1 item. This is because the above issues always (if the program doesn't break) leaves ab == '' and ''.split(' ') => [''] and thus len(ab.split(" ")) => 1
1 tip that I think would help in code comprehension is that the name variable here is not a single name string like it implies. It's actually a list[str]. I'd probably denote the variables something more like names_str: str vs names: list[str] or raw_names vs names. Then just use something like for name in names: and not worry about indexes. You can also use name.endswith('a') instead of name[-1] == 'a' for better readability.
Eventually you can combine these into a list comprehension for maximal succinctness -> len([name for name in names if name.endswith('a') or name.endswith('b')]).
words = ["ab", "bab", "pa", "pap"]
result = 0
for word in words:
if word[-1] in "ab":
result += 1
print(result)
As a list comprehension:
words = ["word1a", "word2b", "word3", "word4", "word5a"] # ['word1a', 'word2b', 'word5a']
filtered_words = [word for word in words if word[-1] in "ab"]
filtered_words = [word for word in words if word.endswith(("a", "b"))] # better, if you have multiple endings you want to search for with different lengths
len(filtered_words) # 3
name[i-1] is the previous name in the list, not the last character of the current name in the loop.
There's no need to append the matching names to a string. If you just need the count of matches, increment a counter variable.
You need to put a and b in quotes to make them strings, not variables.
names = input("Enter list of names: ")
name = names.split(" ")
matches = 0
print("Number of words:", len(name))
for cur_name in name:
if cur_name.endswith('a') or cur_name.endswith('b'):
matches += 1
print("Number of words that end with a or b: ", matches)
Use the endswith string method to detect if the last letter is "a" or "b"
names = ["bob","boba","larry","curly","moe"]
count = 0
for name in names:
if name.endswith("a") or name.endswith("b"):
count += 1
print(f"{count=}") # count=2
I'm having trouble doing the next task:
So basically, I need to build a function that receives a (sentence, word, occurrence)
and it will search for that word and reverse it only where it occurs
for example:
function("Dani likes bananas, Dani also likes apples", "lik", "2")
returns: "Dani likes bananas, Dani also kiles apples"
As you can see, the "word" is 'lik' and at the second time it occurred it reversed to 'kil'.
I wrote something but it's too messy and that part still doesn't work for me,
def q2(sentence, word, occurrence):
count = 0
reSentence = ''
reWord = ''
for char in word:
if sentence.find(word) == -1:
print('could not find the word')
break
for letter in sentence:
if char == letter:
if word != reWord:
reWord += char
reSentence += letter
break
elif word == reWord:
if count == int(occurrence):
reWord = word[::-1]
reSentence += reWord
elif count > int(occurrence):
print("no such occurrence")
else:
count += 1
else:
reSentence += letter
print(reSentence)
sentence = 'Dani likes bananas, Dani also likes apples'
word = 'li'
occurrence = '2'
q2(sentence,word,occurrence)
the main problem right now is that, after it breaks it goes back to check from the start of the sentence so it will find i in "Dani". I couldn't think of a way to make it check from where it stopped.
I tried using enumerate but still had no idea how.
This will work for the given scenario
scentence = 'Dani likes bananas, Dani also likes apples'
word = 'lik'
st = word
occ = 2
lt = scentence.split(word)
op = ''
if (len(lt) > 1):
for i,x in enumerate(lt[:-1]):
if (i+1) == occ:
word = ''.join(reversed(word))
op = op + x + word
word = st
print(op+lt[-1])
Please test yourself for other scenario
This line for i,x in enumerate(lt[:-1]) basically loops on the list excluding the last element. using enumerate we can get index of the element in the list in i and value of element in x. So when code gets loops through it I re-join the split list with same word by which I broke, but I change the word on the specified position where you desired. The reason to exclude the last element while looping is because inside loop there is addition of word and after each list of element and if I include the whole list there will be extra word at the end. Hope it explains.
Your approach shows that you've clearly thought about the problem and are using the means you know well enough to solve it. However, your code has a few too many issue to simply fix, for example:
you only check for occurrence of the word once you're inside the loop;
you loop over the entire sentence for each letter in the word;
you only compare a character at a time, and make some mistakes in keeping track of how much you've matched so far.
you pass a string '2', which you intend to use as a number 2
All of that and other problems can be fixed, but you would do well to use what the language gives you. Your task breaks down into:
find the n-th occurrence of a substring in a string
replace it with another word where found and return the string
Note that you're not really looking for a 'word' per se, as your example shows you replacing only part of a word (i.e. 'lik') and a 'word' is commonly understood to mean a whole word between word boundaries.
def q2(sentence, word, occurrence):
# the first bit
position = 0
count = 0
while count < occurrence:
position = sentence.find(word, position+1)
count += 1
if position == -1:
print (f'Word "{word}" does not appear {occurrence} times in "{sentence}"')
return None
# and then using what was found for a result
return sentence[0:position] + word[::-1] + sentence[position+len(word):]
print(q2('Dani likes bananas, Dani also likes apples','lik',2))
print(q2('Dani likes bananas, Dani also likes apples','nope',2))
A bit of explanation on that return statement:
sentence[0:position] gets sentence from the start 0 to the character just before position, this is called a 'slice'
word[::-1] get word from start to end, but going in reverse -1. Leaving out the values in the slice implies 'from one end to the other'
sentence[position+len(word):] gets sentence from the position position + len(word), which is the character after the found word, until the end (no index, so taking everything).
All those combined is the result you need.
Note that the function returns None if it can't find the word the right number of times - that may not be what is needed in your case.
import re
from itertools import islice
s = "Dani likes bananas, Dani also likes apples"
t = "lik"
n = 2
x = re.finditer(t, s)
try:
i = next(islice(x, n - 1, n)).start()
except StopIteration:
i = -1
if i >= 0:
y = s[i: i + len(t)][::-1]
print(f"{s[:i]}{y}{s[i + len(t):]}")
else:
print(s)
Finds the 2nd starting index (if exists) using Regex. May require two passes in the worst case over string s, one to find the index, one to form the output. This can also be done in one pass using two pointers, but I'll leave that to you. From what I see, no one has offered a solution yet that does in one pass.
index = Find index of nth occurence
Use slice notation to get part you are interested in (you have it's beginning and length)
Reverse it
Construct your result string:
result = sentence[:index] + reversed part + sentence[index+len(word):]
This is where my fill-in-the-blanks game begin. I need help replacing the old sentence with a new sentence when the user answer correctly. I'm still not sure if everything should be done in one function or get a different one. My main function is "def answer_check(answer, sentence, blank_space):". I want to use the other two functionst too (if relevant).The "def replace_the_blank(answer, sentence, blank):" function could need some modifying to respond only when the user correctly guess and to use next string accordingly too... I don't know how to go about it.....
Overall, I need help replacing strings that are from the "blank_space" list in the "driver_Knowledge_test" list, and replace it with the "answer_1" list --- all of which should be in ordert too and when the user correctly guesses... Hope that makes sense.
driver_knowledge_test = ["When you're going to drive it is important to always put on your ___1___, including your passengers.","If there are no lanes marked on the road, you should drive in the ___2___ side of the road.", "It's getting dark and the sun is fading, you should turn on the ___3___. ","Before driving on a freeway, you should make sure you have enough ___4___, oil, water and the correct tyre pressure."]
answer_1 = ['seatbelts', 'left', 'light', 'fuel']
blank_space = ["___1___", "___2___", "___3___", "___4___"]
'''goal: collect user's answer and replace sentence with word when answered correct - other loop to rettry'''
def finding_blank(word, pos):
for ea_blank in word:
if ea_blank in pos: #This equals to teh whole list.
return ea_blank
return None
def replace_the_blank(answer, sentence, blank):
new_list = []
blank_index = 0
answer_index = 0
sentence_index = 0
for ea_element in sentence:
blank_number = finding_blank(sentence[sentence_index], blank)
if blank_number == blank[blank_index]:
blank_number.replace(blank_index, answer[answer_index])
blank_index += 1
answer_index += 1
sentence_index += 1
"Inputs answer list and sentence string"
"Outputs new sentence when answered correctly"
def answer_check(answer, sentence, blank_space):
new_list = []
index = 0
sentence_index = 0
answer_index = 0
blank_index = 0
while index < sentence:
print sentence[sentence_index]
player_answer = raw_input("\nType your answer for " + blank_space[blank_index] + " \n>>>")
if player_answer.lower() == answer[answer_index]:
new_list.append(sentence[sentence_index])
answer_index += 1
sentence_index += 1
index += 1
blank_index += 1
#print replace_the_blank(answer, sentence, blank)
print "CCORRECT! \n"
else:
print "Wrong! Try again. :) \n"
answer_check(answer_1, driver_knowledge_test, blank_space)
You may use string replace method to replace a part of string with another string.
So instead of
print replace_the_blank(answer, sentence, blank)
try
print sentence[sentence_index].replace(blank_space[blank_index], answer[answer_index])
I have a program in which a user picks a letter. The program should then search through a list and count how many names start with the letter the user chose.
This is what I've got so far:
nameslist = ["bob", "phil", "james"]
letter = input("Pick a letter.")
letter = letter.lower()
wordcount = 0
for I in range(len(nameslist)-1):
if list[I].startswith(letter):
wordcount = wordcount+1
print(list[I])
I was led to believe that startswith would help me but it doesn't work.
You could use the following:
names = ["bob","phil","james"]
letter = input("Pick a letter.")
letter = letter.lower()
count = 0
for name in names:
if name.startswith(letter):
print(name)
count += 1
This iterates over each name in names and uses the startswith() method to check whether name begins with letter. If name begins with letter, it prints name. It also counts the number of name in names that begin with letter using the count variable.
If you want to keep your current code all you need to do is fix some typos. Here is the correct code with comments showing what I changed:
nameslist=["bob","phil","james"]
letter=input("Pick a letter.")
letter=letter.lower()
wordcount=0
for I in range(len(nameslist)): # you dont need the -1 at the end of this
if nameslist[I].startswith(letter): # you need to change list to nameslist
wordcount=wordcount+1
print(nameslist[I]) # you need to change list to nameslist
I'm trying to make a program using python for class that works like this:
'Enter a word: " (EG Stack)
Then it outputs
S
St
Sta
Stac
Stack
I believe that it would use a looping function, but I'm completely stuck!
You can use slicing to achieve your output. Each iteration of the for loop increments an index variable (i below), and this is used to display ever increasing slices from the string.
>>> word = 'Stack'
>>> for i in range(1, len(word)+1):
... print word[:i]
...
S
St
Sta
Stac
Stack
>>> word='Slicing'
>>> for i in range(1, len(word)+1):
... print word[:i]
...
S
Sl
Sli
Slic
Slici
Slicin
Slicing
You can read about slicing in the Python tutorial.
msg = raw_input("Enter a word: ") #raw_input will convert the input into a string
#otherwise it would crash without quotation marks
word = "" #Initialize a variable
for letter in msg: #Cycle through each letter
word += letter #Adds that letter to your string
print(word) #Prints out the current letters
http://pastebin.com/CDzNfdbJ
Got it, I don't really understand it, but it works.