Program: Words after "G"/"g" (python) - python

I have recently started to learn python as I wanna enter a deep learning field in future.
As I'm completely new and only started I apologize in advance if my question is silly.
I am currently doing a course on edx by name introduction to python fundamentals and as I final project of module 1 I need to make a program that asks for user input and give an output of all words that starts from h to z.
task
here is my code:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
new_name = ""
for letter in user_input:
if letter.isalpha() == True:
new_name += letter.upper()
elif letter.isalpha() == False:
if new_name[0] > "g":
print(new_name)
new_name = ""
else:
new_name = "\n"
print(new_name)
INPUT = Wheresoever you go, go with all your heart
OUTPUT = WHERESOEVERYOUGOGOWITHALLYOURHEART
By my understanding of code I have wrote:
- user enters input
- code check for each character
- if letter is alpha that letter is added into new_name variable
- when encounter first no alpha character in these case space after word Wheresoever code moves to elif since after checking a fist one it was not True and elif turn to mach criteria
- then by using nested if statement it checks if new_name variable[index0] (Wheresoever) is grater then g.
- if it is grater it prints new_name and makes new_name empty and repeat the circle until there is no more characters to check.
- if its not greater then g it starts with new word on the new line
Now as I sad I'm completely new so I have just described my thoughts process of the code and please tell me where am I wrong and how can I corrected and improve my thoughts process and the code mentioned above.
Thank you in advance :)

Try the below, iterate trough the list split of the user_input string, then check if it starts with a G or g, if it does, don't keep it, otherwise keep it, then use regular expressions (re) to get only letters.
Also as you said you need isalpha so then:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
print('\n'.join([''.join(x for x in i if x.isalpha()).upper() for i in user_input.split() if not i.lower().startswith('g')]))
Example output:
enter a 1 sentence quote, non-alpha separate words: Wheresoever you go, go with your heart
WHERESOEVER
YOU
WITH
YOUR
HEART
Update form #KillPinguin:
do:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
print('\n'.join([''.join(x for x in i if x.isalpha()).upper() for i in user_input.split() if ord(i[0])>ord('g')]))

Related

Conversion Program

I have a program where I need to prompt the user for an input of a word and a key. Next, the program should remove all the spaces, punctuation and all numbers from the word and convert all the letters into uppercase. Once that is done I need the program to replace all the characters of the word with the key. So if the word is a library, and the key is moose, the program should print out moosemo. I know that this part includes something like append.key(len plaintext) something of this fashion, but I'm not exactly sure how. I don't have a lot of the code done because I am pretty lost. Here is what I have so far:
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
print(phrase.upper()) #converts all characters from phrase to uppercase
If anyone knows what to do or what to change, please let me know. Please show the change in code with your response. Thanks in advance
I used answers from here and here to make compose this.
Here is one way you might do it, using the string class to get rid of punctuation and numbers.
import string
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
#replace - gets rid of spaces
#first translate - gets rid of punctuation
#second translate - gets rid of digits
#upper - capitalizes.
phrase = phrase.replace(" ", "")\
.translate(str.maketrans('', '', string.punctuation))\
.translate(str.maketrans('','',string.digits))\
.upper()
times_to_repeat = len(phrase)//len(encryptionkey)
leftover_length = len(phrase)%len(encryptionkey)
#multiply string by how many times longer it is than the encryption, then add remaining length.
#in python you can do 'string'*2 to get 'stringstring'
final_phrase = encryptionkey*times_to_repeat+encryptionkey[:leftover_length]
print(final_phrase)
Output:
# Only keep the alphabet characters
phrase = ''.join(c for c in phrase if c.isalpha())
# Add the encryption key at least 1 more times than divisible (to count for remainder)
# and slice the output to the length needed
phrase = (encryptionkey * (1 + len(phrase) // len(encryptionkey)) [:len(phrase)]

How do I get the position of a string inside a list in Python? [duplicate]

This question already has answers here:
How to get the position of a character in Python?
(11 answers)
Closed 1 year ago.
I am trying to get the position of a string inside a list in Python? How should I do it?
For example, when a user provides a sentence "Hello my name is Dolfinwu", I turn the entire sentence into a list beforehand, and I want to get the positions of each "o" right here, how can I do it? In this case, the position of the first "o" is "4", and the position of the second "o" is "18". But obviously, users would enter different sentences by using different words, so how can I get a specific string value's position under this unpredictable situation?
I have tried this code as below. I know it contains syntax errors, but I could not figure out something better.
sentence = input('Please type a sentence: ')
space = ' '
for space in sentence:
if space in sentence:
space_position = sentence[space]
print(space_position)
How about this one? I figured another solution out yesterday.
import re
sentence = input('Please type a sentence: ')
print([match.span()[0] for match in re.finditer(' ', sentence)])
This code of yours is messed up a bit
space = ' ' # This is fine but redundant
for space in sentence: # Shouldn't reuse variable names. Should be <for char in sentence. But I wouldn't use that either since we don't need the char it self but the index
if space in sentence: #Should be <if char == space> Your just returns a True if there's a single space anywhere in the string. Assuming it's using the correct variable named space. Honestly I don't know what this code will do since I didn't run it :P
space_position = sentence[space]
print(space_position)
Here's what I would do, which could be done better since I'm a beginner too.
sentence = input('Please type a sentence: ')
for i in range(len(sentence)):
if sentence[i] == " ":
print(i)
#>>>Please type a sentence: A sentence and spaces
#>>>1
#>>>10
#>>>14
There is also an error in your first code, where the line space_position = sentence[space] uses a string, if I am correct, as the index of the list in the line, which I believe should be an integer. So what I would do would be like
sentence = input('Please type a sentence: ') # Asks the user to input the sentence
space_position = [] # The list where the list indexes of the spaces will be stored (can work for any other symbol)
for i in range(len(sentence)): # Scans every single index of the list
if sentence[i] == " ": # Determines whether if the value of the specific list index is the chosen string value
# (The value could be swapped for another one aside from strings)
print(i) # Print out the index where the value is the chosen string value
The rest of the cost are like what #pudup posted
P.S. I am also a beginner, so my code may not be the best solution or have syntax errors, apologies if they do not work or are not very efficient.

Censoring the given word in a text

I am a beginner in Python. This is a challenge that I've found in a forum.
This program is censoring the words' (which has given by the user) letters with "*" except the first letter.
For example, If the sentence is "Every breath you take every move you make" and the input word is "every", the output should look like this:
2 incidents found.
Censored lyrics:
E**** breath you take e**** move you make
This was my only idea but it did not work.
text=input("Enter your text: ").lower()
word=input("Choose a word from the previously entered text: ").lower()
def censor(text,word):
t=text.split()
n=[]
for i in t:
if(i==word):
n.append("*"*len(word))
else:
n.append(i)
return " ".join(n)
print (censor)
Any help would be appreciated!
There are a few mistakes.
In Python 3 you have to use () while printing e.g. print("Hello world") NOT: print "Hello world"
i.lower()==word because "Every" != "every"
n.append(i[0]+"*"*(len(word)-1)) because you want first letter to stay
Code:
text=input("Enter your text: ").lower()
word=input("Choose a word from the previously entered text: ").lower()
def censor(text,word):
t=text.split()
n=[]
for i in t:
if(i.lower()==word):
n.append(i[0]+"*"*(len(word)-1))
else:
n.append(i)
return " ".join(n)
print(censor(text,word))
The issue here is that when you find the word, you just put * you never add the first letter. To fix that you would need:
n.append(word[0]+"*"*(len(word)-1))
instead of
n.append("*"*len(word))
Now it will add the first letter and the right number of * afterward.
It's not clear how it "doesn't work"; when I run your code this is the output:
***** breath you take ***** move you make
We can tweak your script to leave in the first letter:
if(i==word):
n.append(i[0] + "*"*(len(word)-1))
Giving the output as:
e**** breath you take e**** move you make
Again, it's not actually clear what wasn't working, but that's how you'd show the first letter of each censored word.
I have an approach related to Regex which could suit this purpose, just consider this as something you can expand on thinking to create your final program:
import re
blacklist = ['every']
def replace(match):
word = match.group()
if word.lower() in blacklist:
return word[0]+"*"*(len(word)-1)
else:
return word
text = 'Every breath you take every move you make'
text = re.sub(r'\b\w*\b', replace, text, flags=re.I|re.U)
print(text)
The advantage this has is that it will work with all kinds of word boundaries that regex recognizes.
You can check the output image below:

Hangman game project

I'm trying to a hangman game. I already achieved to set the basics of the game (list, interaction with user) but I don't know how to do the lines for the game, keep asking and printing what the user correct answers are and ilustrate the hangman.
I used index in order to search the exact location of the letter in the word, but I dont know to print it, depending on the number and also I don't how to code that the program keeps track of the correct words.
I would be totally glad for your help. Also thanks for your patience.
The first part of the code is well coded but stackoverflow doesn't display it right.
------------------------------------------------------------------------
import random
def hangman():
words = ['house','car','women', 'university','mother', 'school', 'computer','pants'] #list of words
computer = words[random.randint(0,6)] #computerchoice
word = list(computer) #Make a list with each letter of the word.
welcome = (input ('Welcome, type ok to continue: '))
if welcome == 'ok':
length = len(word)
print(f'help? the word has {length} letters')
option = (input('Start guessing, letter by letter'))
count= 0 #count takes the count of how many tries.
chances = length+3 #You are able to make 3 mistakes.
while count<=chances:
if option in word: #if the choice is there
place = word.index(option) #search for the place.
print() #dont know how to print it in 'that' place.
#place the correct letter over that line.
print('_ '*length) #Trying to do the under lines.
count+=1
else:
break
#Dont know to ilustrate the hangman depending on the length of the word.
hangman()
First let's analyse your code:
import random
def hangman():
words = ['house','car','women', 'university','mother', 'school','computer','pants'] #list of words
computer = words[random.randint(0,6)] #computerchoice
word = list(computer) #Make a list with each letter of the word.
Everything is fine up to here , although str can be used the same way as a list , so no need to transform it.
welcome = (input ('Welcome, type ok to continue: '))
if welcome == 'ok':
length = len(word)
print(f'help? the word has {length} letters')
Yes but those are not unique letters. You can use set() to have the number of unique letters.
option = (input('Start guessing, letter by letter'))
If your input starts here, you will only ask once for a letter , you need to include this part in the while loop
count= 0 #count takes the count of how many tries.
chances = length+3 #You are able to make 3 mistakes.
This would then probably be changed to the length of the set.
while count<=chances:
if option in word: #if the choice is there
place = word.index(option) #search for the place.
This will only give you the index of the first occurence.
We should keep in mind to use regex for this type of search : Find all occurrences of a substring in Python
print() #dont know how to print it in 'that' place.
Let's remember to use the print formating f'stufff{value}stuffff'
#place the correct letter over that line.
To do it , you need to create a str only with _and then fill it in with the indexes using list comprehension .
print('_ '*length) #Trying to do the under lines.
count+=1
Maybe we should handle what happens if option is not in words ?
else:
break
#Dont know to ilustrate the hangman depending on the length of the word.
Also there is no need for break : count increments and therefore while will terminate. And if it was for the outer if/else , break doesn't work outside a loop.
hangman()
Question for OP:
What point would you like to sort out yourself ? What do you need help for next ?

Coding a language translator

im trying to code a kind of language translator from any language to a kind of gibberish language, wheres every consonant will be replaced with the same consonant plus an o and then the consonant again.
b = bob
d = dod
f = fof
so the text "Hi my name is x"
will become "Hohi momy nonamome isos xox"
The problem i have is the converting part.
any tips on how i can proceed?
Oh and btw I am using python 3
What i got this far.
#Welcom text
print ("Gibberish translator!")
#get stentence
original = raw_input("Give a sentence: ")
#Check so that it is a correct sentence
if len(original) > 0:
print ("")
else:
print ("give a real sentence..: ")
#convert
gibberish = ""
for i in original:
if i == "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z":
i = i + "0" + i
gibberish.append(i)
elif i == "a,o,u,e,i,y":
gibberish.append(i)
#print out the gibberish
print (gibberish)
Yeah! i think i got it to work quite well..
# -*- coding: cp1252 -*-
#Repeat
while True :
#Welcom text
print ("Gibberish translator!")
#get stentence
original = raw_input("Give a sentence: ")
#Check so that it is a correct sentence
if len(original) > 0:
print ("")
else:
print ("Give a real sentence..: ")
#convert
gibberish = ""
for i in original:
if i in "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ":
i = i + "o" + i
gibberish = gibberish + i
elif i in "aoueiyåäö AOUEIYÅÄÖ":
gibberish = gibberish + i
#print out the gibberish
print (gibberish)
print ("\n")
Im open for suggestions to make it "better"
The problem is you're comparing a character i to a string "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z". The two will never be equal.
What you want to do instead is use the in operator.
if i in 'bcdfghjklmnpqrstvwxz':
Also, strings don't have an .append() method, only lists do.
You can create a string from a list of strings by doing ''.join(my_list)
If and in statements don't work like that. This is actually a very common mistake, so no worries. When you get to the if i == "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z": python reads that as "if i is all of this string (the string that contains all the consonants). Now unless you enter that string exactly somewhere in your sentence, python is going to think "nope no string like that" and skip it. You have the same problem with your vowel statements.
For the fastest fix:
if i in "bcdfghjklmnpqrstvwxz": #note the removal of commas, don't want them getting "o'd"
#rest of your code for consonants
else: #having an else is often very good practice, or else you may not get a result.
#what to do if its not a consonant
The function checks if it is a lower case vowel (might want to add stuff for upper case letters), then if it isn't, it checks if it is a letter period. string is very useful when working with strings. You should look at the docs.
And finally, you need to change append to just use + with strings.

Categories

Resources