Removing 1 letter each time from the word - python

I am trying to make a program that asks for a word, and then prints it to the console multiple times, each time removing the first character until the word ends. Program also asks if the word should be printed as shown or backwards.
The printing action is the same regardless if the word should be printed forwards or backwards.
The output should be something like this:
Give a word: milkfloat
Print forward? (yes/no): yes
milkfloat
ilkfloat
lkfloat
kfloat
float
loat
oat
at
t
Give a word: hippopotamus
Print forward? (yes/no): no
sumatopoppih
umatopoppih
matopoppih
atopoppih
topoppih
opoppih
poppih
oppih
ppih
pih
ih
h
I am trying but I cant figure out how to do it. Can anybody help?

Use the input() function to get some input from the command line e.g.
word = input('Enter word: ')
print(word)
>>> Enter word:
>>> Enter word: dog
>>> 'dog'
Use the print() function to print strings e.g.
word = 'dog'
print(word)
>>> 'dog'
Use an if statement to evaluate a condition e.g.
word = 'dog'
if word == 'dog':
print('I love dogs!')
elif word == 'cat':
print('I am more of a dog person...')
else:
print('Do you not like animals?')
>>> I love dogs!
Use [] square brackets to slice strings into the pieces you want e.g.
word = 'dog'
print(word[:-1])
>>> 'do'
print(word[1:])
>>> 'og'
Use the len() function to work out the length of a string e.g.
word = 'dog'
print(len(word))
>>> 3
Use a for loop with range() to do something a certain number of times e.g.
for i in range(3):
print(i)
>>> 0
>>> 1
>>> 2
I'll leave the rest to you.

def printer(word):
for i in range(len(word)):
print(word[i::])
text = input("Give a word: ")
forward = input("Print forward? (yes/no): ")
if forward=="yes":
printer(text)
else:
printer(text[::-1])

So this is something that I've set a friend to do as an exercise to get more comfortable with python.
The exercise is called "word pyramids" and this is the answer that I came up with (so that they have something to refer to later if they get stuck):
def print_backwards_word_pyramid(word):
for i in range(0, len(word)):
if i == 0:
print(word[::-1])
else:
print(word[:i-1:-1])
return
and this will print, for the word "juice"
eciuj
eciu
eci
ec
e
But, if you want something a little bit more elegant, the back half can be done as:
def print_backwards_word_pyramid(word):
for i in range(0, len(word)):
print(word[i:][::-1])
return
... which if read from right to left (for those who need a hand with what this is telling python) says:
In reverse, the slice starting at the "i'th" character, of the string value of variable "word", print.

Related

Find words in a sentence and its index position using a for loop

I am writing a code that prompts the user to enter a sentence which is then defined as str1 and then is prompted to enter a word defined as str2.
For example:
Please enter a sentence: i like to code in python and code things
Thank you, you entered: i like to code in python and code things
Please enter a word: code
I want to use a for loop to find str2 in str1 to print whether the word is or is not found, and if it has been found, the index position(s) of str2.
Currently I have this code:
str1Input = input("Please enter a sentence: ")
print("Thank you, you entered: ",str1Input)
str1 = str1Input.split()
str2 = input("Please enter a word: ")
if str2 in str1:
for str2 in str1:
print("That word was found at index position", str1.index(str2)+1)
else:
print("Sorry that word was not found")
Although, the outcome appears to print whether or not the index position was found but then prints the index position of every word inside the sentence. Also if I am searching of a certain word that appears twice in that sentence, it just prints the index position of the first time the word is seen in the sentence, for example:
Please enter a sentence: i like to code in python and code things
Please enter a word: code
Thank you, you entered: i like to code in python and code things
That word was found at index position: 1
That word was found at index position: 2
That word was found at index position: 3
That word was found at index position: 4
That word was found at index position: 5
That word was found at index position: 6
That word was found at index position: 7
That word was found at index position: 4
That word was found at index position: 9
If anyone could help me and anyone else attempting something similar to this that would be extremely helpful!
You can use a conditional list comprehension (it's like a for-loop):
>>> str1 = 'i like to code in python and code things'
>>> str2 = 'code'
>>> indices = [idx for idx, word in enumerate(str1Input.split(), 1) if word == str2]
>>> indices
[4, 8]
Giving you the indices of the matches. Then you can do whatever you like with those:
if indices:
for idx in indices:
print('word found at position {}'.format(idx)
else:
print('word not found')
Your attempt actually wasn't too bad but you did one mistake: for str2 in str1: this overwrites your str2 variable which holds the string to look for! Also index will always give you the first index of your variable so when you did str1.index(str2)+1 you looked for the first occurence of the currently investigated item! That's why you had That word was found at index position: 4 two times because it only looked for the first 'code'.
The documentation is always useful to read:
list.index:
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
Use the enumerate python built-in function:
for index, word in enumerate(splitted_sentence):
if word == target_word:
print("Index: ", index)
docs: https://docs.python.org/3.3/library/functions.html#enumerate
UPD: list.index() method returns the lowest index of matching element. That's why you always get same index if your word appears twice in a sentence.
Check the docs on this as well: https://docs.python.org/3.6/tutorial/datastructures.html#more-on-lists
Just make sure to use comparisons in if/else statements and think about what your loop is doing.
Hope this is simple enough but effective:
EDIT: Add a counter rather than using ".index()". Just keeps it nice and basic:
str1In = "I like to code a few things and code a lot"
str2 = "code"
str1 = str1In.split()
indexCount = 0
for word in str1:
if word == str2:
print("Your word was found at index point",int(indexCount))
else:
print("Your word was not found at",int(indexCount))
indexCount += 1
Your problem is in for loop: you assign values from str1 to local variable str1 each iteration. It's called variable shadowing.
The solution is to use different variable name in loop declaration.
What you can do is make a list out of str1 and find where str2 occurs in the list. Here is the code:
str1 = "i like to code in python and code things"
str2 = "code"
the_indexes = []
the_new_list = [str1.split(' ')]
the_count = str1.count(str2)
if the_count > 0:
for i in range(len(the_new_list[0])):
if the_new_list[0][i] == str2:
the_indexes.append(i)
else:
print str2, " not found in the first sentence"
print "The indexes are: "
for i in the_indexes:
print i

Python Case Matching Input and Output

I'm doing the pig latin question that I'm sure everyone here is familiar with it. The only thing I can't seem to get is matching the case of the input and output. For example, when the user enters Latin, my code produces atinLay. I want it to produce Atinlay.
import string
punct = string.punctuation
punct += ' '
vowel = 'aeiouyAEIOUY'
consonant = 'bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ'
final_word = input("Please enter a single word. ")
first_letter = final_word[:1]
index = 0
if any((p in punct) for p in final_word):
print("You did not enter a single word!")
else:
while index < len(final_word) and (not final_word[index] in vowel):
index = index+1
if any((f in vowel) for f in first_letter):
print(final_word + 'yay')
elif index < len(final_word):
print(final_word[index:]+final_word[:index]+'ay')
What you need is str.title(). Once you have done your piglatin conversion, you can use title() built-in function to produce the desired output, like so:
>>> "atinLay".title()
'Atinlay'
To check if a string is lower case, you can use str.islower(). Take a peek at the docs.
simply use the built in string functions.
s = "Hello".lower()
s == "hello"
s = "hello".upper()
s == "HELLO"
s = "elloHay".title()
s == "Ellohay"

Creation of a Function that transforms sentence in Python

So I am trying to create a function that calls two functions within the function where one function called "encode" checks if the first letter of a word is a vowel and if yes it will add "way" to the end of the word and if the word starts with a consonant it will move the first letter to the third position in the word and adds gar.
my problem is creating that function that calls from the encode function to read a sentence and change each word accordingly based on the first letter.
So here are some text cases for the function:
encode() function:
The output will look like this:
Please enter your message: python is fun
The secret message is: ythonpar isway unfar
translation is correct when words are separated by more than one space character.
Please enter your message: simple is better than complex
The secret message is: implesar isway etterbar hantar omplexcar
Here is my script. They are suppose to be connected.
def get_input():
user_input = input('Please enter a message: ')
more_message = True
while more_message:
user_input = input('Please enter a message: ')
if not user_input==' ':
more_grades = False
return
def starts_with_vowel(word):
while True:
data = word
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
print ('true')
else:
print ('false')
return
def encode(word):
while True:
data = starts_with_vowel(word)
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
new_word=word+'way'
print ('The secret word is:',new_word)
else:
new_word2=word+'ar'
scrambled_word=new_word2[1:-2]+new_word2[0]+new_word2[3]+new_word2[4]
print (scrambled_word)
print ('The secret word is:',new_word2)
return
def translate(text):
secret_message= encode(text)
return (secret_message)
translate('gin is a boy')
A better approach would be to use split on the sentence (input) and loop over the words:
vowels = 'aeiou'
sentence = 'python is fun'
new_words = []
for word in sentence.split():
if word[0].lower() in vowels:
new_words.append(word+'way')
else:
new_words.append(word[1:3]+word[0]+word[3:]+'gar')
' '.join(new_words)
'ytphongar isway unfgar'
I think in the first part of the code you will need to change the more_grades section with more_message, because first off more_grades has not been initialized and more_messages is controlling your loop so i think that's what you meant to do. Don't worry I believe that's only one error I have caught I will check the rest of the code and get back to you. Don't stress it.Happy coding :-)

Building a word up with a loop

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.

How to make inputed text vise versa in python?

I try write program that build new word from inputed, where letter is vise versa
# vise versa
print ("word vise versa")
word = input("Input your text ")
new_word = ""
while word:
position = len(word) - 1
for letter in word:
new_word += letter[position]
position -= 1
print(new_word)
Always have mistake
Traceback (most recent call last):
File "4_2.py", line 9, in <module>
new_word += letter[position]
IndexError: string index out of range
what I do wrong?
Thanks!
The trouble is probably what you are doing in the below lines
for letter in word:
new_word += letter[position]
where letter will be each letter within the word, first 'a' then 'b' then 'c' if word was abc. On the seconds string you are trying to use the letter 'a' as an array, which is no good. You probably want to offset into the word array instead?
First in your code, if your input is not None or a False Value, your loop will go forever because word is not a False Value.
Second, you can use reverse slice of a string or a list like this:
# vise versa
print("word vise versa")
word = raw_input("Input your text ")
new_word = ""
if word:
new_word = word[::-1]
print(new_word)
Get Input word from user by using raw_input method
Get length of input word by len method.
Use while loop to add character in new variable.
decrement length variable by 1
print "Program: word vise versa"
word = raw_input("Input your text:")
new_word = ""
wdlen = len(word)
while wdlen:
new_word += word[wdlen-1]
wdlen -= 1
print new_word
Output:
$ python test.py
Program: word vise versa
Input your text:abcdef
fedcba
use slice .
more info https://docs.python.org/2/whatsnew/2.3.html#extended-slices
>>> a = "12345"
>>> a[::-1]
'54321'
You can rewrite your code as a a oneliner like this:
new_word = "".join(reversed(input("Input your text ")))
The reversed function takes a sequence type, and returns a new one with the elements in reverse order. However, this will now be a list.
The "".join then joins them back into a string - some join string must be provided, so any empty string is used.
With fewer lines, and no temporary variables, there are fewer places for this code to break.

Categories

Resources