Randomize Fill In The Blank - python

Despite this fill-in-the-blank script working successfully, I am unsure of how to randomly assign blanks. As can be seen, I placed two blanks between 5-7. However, I would like to randomize where they're set.
sentence = """Immigration is an issue that affects all residents of the United States, regardless of citizenship status"""
sentence0 = sentence.split(" ")
max = len(sentence)
sentence1 = sentence0[0:5]
sentence1 = " ".join(sentence1)
sentence2 = sentence0[7:max]
sentence2 = " ".join(sentence2)
Overall = sentence1 + " _ _ " + sentence2
print(Overall)
test = input()
Overall2 = sentence1 + " " + test + " " + sentence2
print(Overall2)
start = "\033[1m"
end = "\033[0;0m"
if Overall2 == sentence:
print(start + "Correct" + end)
else:
print(start + "Incorrect" + end)

This is simple and is working :
import random
sentence = "Immigration is an issue that affects all residents of the United States, regardless of citizenship status"
words = sentence.split(" ")
#SELECT RANDOM WORD FOR PLACING BLANK
rand_index = random.randint(0, len(words)-1)
#KEEP A BACKUP OF THE WORD
word_blanked = words[rand_index]
#REPLACE WORD WITH BLANK
words[rand_index] = "_____"
#MAKE BLANKED SENTENCE AND CORRECT ANSWER
blanked_sentence = ""
correct_answer = ""
for word in words:
blanked_sentence = blanked_sentence + word + " "
if word == "_____":
correct_answer = correct_answer + word_blanked + " "
else:
correct_answer = correct_answer + word + " "
print(blanked_sentence)
answer = input("Enter your answer : ")
if answer == word_blanked:
print("Correct Answer!")
else:
print("Wrong Answer!")
print("Correct Answer is : ")
print(correct_answer)

Something like this:
import random
sentence = """Immigration is an issue that affects all residents of the United States, regardless of citizenship status"""
sentence0 = sentence.split(" ")
# removed overlap with "max"
max_length = len(sentence0)
# generate a random slice based on the length of the sentence.
random_slice = random.randrange(0, max_length)
sentence1 = sentence0[0:random_slice ]
sentence1 = " ".join(sentence1)
# increment two words forward from the random slice
sentence2 = sentence0[random_slice + 2: max_length]
sentence2 = " ".join(sentence2)
Overall = sentence1 + " _ _ " + sentence2
print(Overall)
test = input()
Overall2 = sentence1 + " " + test + " " + sentence2
print(Overall2)
start = "\033[1m"
end = "\033[0;0m"
if Overall2 == sentence:
print(start + "Correct" + end)
else:
print(start + "Incorrect" + end)

Generic example:
import random
sentence = 'The quick brown fox jumps over the lazy dog'
# convert sentence from string to list
sentenceList = sentence.split(' ')
# get random location of the element to be replaced
locToReplace = random.randrange(0, len(sentenceList))
# replace with blanks
sentenceList[locToReplace] = '_ _'
# convert back to string
updatedSentence = ' '.join(sentenceList)
print(updatedSentence)

Related

How to reverse particular string in an input string and return the whole string, with reversed part?

I am having problems with what was said in the title. Basically I am given sentences which contain addresses - I am to reverse only the address in the sentence and return the string. I can reverse the address fine but I am having troubles returning the whole string. My code: ( edit :now corrected):
def problem3(searchstring):
"""
Garble Street name.
:param searchstring: string
:return: string
"""
flag = 0
output = ""
#each word is considered in loop
for i in searchstring.split():
if i.endswith('.'): #if the word ends with .
flag = 0
stype = i
output += " " + stype
elif flag == 1: #if the flag is 1
#street =
output += " " + i[::-1]
elif i.isdigit(): #if the word is digit
flag =1
#num = i
output += i
else:
output += i + " "
#address = num + " " + street + " " + stype
return output
Try this
def problem3(searchstring):
"""
Garble Street name.
:param searchstring: string
:return: string
"""
flag = 0
street = ""
stri=""
#each word is considered in loop
for i in searchstring.split():
if i.endswith('.'): #if the word ends with .
flag = 0
stype = i
continue
if flag == 1: #if the flag is 1
street = street + " " + i[::-1]
continue
if i.isdigit(): #if the word is digit
flag =1
num = i
continue
stri=stri+' '+i
address =stri+" "+ num + " " + street + " " + stype
return address
Then if you call the function:
print(problem3('The EE building is at 465 Northwestern Ave.'))
print(problem3('Meet me at 201 South First St. at noon'))
output will be
The EE building is at 465 nretsewhtroN Ave.
Meet me at at noon 201 htuoS tsriF St.
Instead of using 'if' several times you can use the below code or you can use continue also:
def problem3(searchstring):
"""
Garble Street name.
:param searchstring: string
:return: string
"""
flag = 0
address = ""
#each word is considered in loop
for i in searchstring.split():
if i.endswith('.'): #if the word ends with .
flag = 0
stype = i
address += " " + stype
elif flag == 1: #if the flag is 1
#street =
address += " " + i[::-1]
elif i.isdigit(): #if the word is digit
flag =1
#num = i
address += i
else:
address += i + " "
#address = num + " " + street + " " + stype
return address
print(problem3('The EE building is at 465 Northwestern Ave.'))

Removing extra whitespace between words using for loop Python

I need to remove all excess white space and leave one space, between my words while only using if and while statements. and then state the amount of characters that have been removed and the new sentence
edit, it must also work for punctuation included within the sentence.
This is what I have come up with however it leaves me with only the first letter of the sentence i choose as both the number, and the final sentence. can anyone Help.
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
return result
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
Your code should be something like this:
def cleanupstring(S):
counter = 0
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
counter += 1
else:
lasti = i
result += i
return result, counter
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
The counter keeps track of how often you remove a character and your [0] and [1] work now the way you want them to.
This is because outputList is now a tuple, the first value at index 0 is now the result and the second value at index 1 is the counter.

Different methods to create exceptions to capitalizing a string

Is there another to have exception for capitalizing an entire sentence. I've heard of skipList method, but it didn't work for my code. See below:
string = input('Enter a string: ')
i = 0
tempString = ' '.join(s[0].upper() + s[1:] for s in string.split(' '))
result = ""
for word in tempString.split():
if i == 0:
result = result + word + " "
elif (len(word) <= 2):
result = result + word.lower() + " "
elif (word == "And" or word == "The" or word == "Not"):
result = result + word.lower() + " "
else:
result = result + word + " "
i = i + 1
print ("\n")
print (result)
Sure. Write a complete list of words that should not be title-cased ("and", "the", "or", "not", etc), and title-case everything else.
words = s.split(' ')
result = ' '.join([words[0]] + [w.title() for w in words[1:] if w not in skipwords])
of course this will still miss Mr. Not's last name, which should be capitalized, and some stranger things like "McFinnigan" will be wrong, but language is hard. If you want better than that, you'll probably have to look into NTLK.
You could rewrite this like this
skip_words = {w.capitalize(): w for w in 'a in of or to and for the'.split()}
words = string.title().split()
result = ' '.join(skip_words.get(w, w) for w in words).capitalize()

Recreating sentences with numbers

So I have developed a code which lets you recreate a sentence but there is one problem,it cuts out a word! I don't know why so if somebody can correct it that would be brilliant thanks!
Sentence = input("Please enter a sentence: ")
Sen = Sentence.split()
remove=(",")
numbers = input("Enter Numbers(Separating them with a comma for example 1,3,2): ")
newnumbers = ""
for char in numbers:
if char not in remove:
newnumbers = newnumbers + char + " "
numlist = newnumbers.split()
length = len(numlist) -1
del numlist[length]
savenum = " ".join(numlist) -1
file = open("Bruh.txt","w")
file.write(Sentence)
file.write("\n"+savenum)
file.close()
newli = []
for char in numlist:
newnum = (int(char)-1)
newli = newli + [Sen[int(newnum)]]
words = " ".join(newli)
print("Original Sentence: ",Sentence)
print("Recreated Sentence: ", words)
These lignes are responsible for that behaviour :
# length = len(numlist) -1 # <==== comment these lines
# del numlist[length] # <==== comment these lines
Put them in comments, or remove them :
Sentence = input("Please enter a sentence: ")
Sen = Sentence.split()
remove=(",")
numbers = input("Enter Numbers(Separating them with a comma for example 1,3,2): ")
newnumbers = ""
for char in numbers:
if char not in remove:
newnumbers = newnumbers + char + " "
numlist = newnumbers.split()
# length = len(numlist) -1 # <==== comment these lines
# del numlist[length] # <==== comment these lines
savenum = " ".join(numlist) -1
file = open("Bruh.txt","w")
file.write(Sentence)
file.write("\n"+savenum)
file.close()
newli = []
for char in numlist:
newnum = (int(char)-1)
newli = newli + [Sen[int(newnum)]]
words = " ".join(newli)
print("Original Sentence: ",Sentence)
print("Recreated Sentence: ", words)

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories