The program asks for a string and outputs the string remaining after removing groups of 3 or more meaning it can be 3, 4, 5, 6, and so on, consecutive identical characters. The removal of the groups continues until no more groups are found to be removed. The program should allow repetition until the user does not want to continue. The code must only use while, if, elif, else and no other functions
#Message
print("Hello! Welcome to Candy Crush!") #Introduces user to the application
#Input data
while True:
decision = str(input("Would you like to add a string? ")) #Asks the user if they would like to enter a string.
#Process data
if decision == "Yes" or decision == "yes": #If the user answers yes, it continues but if the user answers something else other than yes and no, it repeats the option.
stringInput = str(input("Please enter a string: ")) #Asks the user to enter the string.
charactersInput = list(stringInput) #Stores the user input in a list.
print("Your original list is", charactersInput)
print("Your original string: ", stringInput)
idx = 0 #This number helps to keep track of what letter the program is processing.
while idx < len(charactersInput) - 2:
if charactersInput[idx] == charactersInput[idx + 1] == charactersInput[idx + 2]:
charactersInput.pop(idx) #The code removes the first index letter.
charactersInput.pop(idx) #The code removes the second index letter.
charactersInput.pop(idx) #The code removes the third index letter. Once the three letters have been removed the next letters take their place.
idx = 0
else:
idx += 1 #One is added to the index to see if the new index number is followed by repeated letters.
result = "".join(charactersInput)#After the code has ran, the following code takes all the results and adds the strings to charactersInput. The information is stored in the variable result.
#Output data
print("The output of your string is: ", result,"\n") #Prints the information stored in result. The information does not include the consecutive letters.
if decision == "No" or decision == "no":
print("Thank you for playing! Have a great day!") #The user is shown a goodbye message and the code ends.
exit() #The application ends if the user answers no
pop is not allowed. Use remove instead. Also, no use of break.
Code:-
#Message
print("Hello! Welcome to Candy Crush!") #Introduces user to the application
#Input data
while True:
decision = str(input("Would you like to add a string? ")) #Asks the user if they would like to enter a string.
#Process data
if decision == "Yes" or decision == "yes": #If the user answers yes, it continues but if the user answers something else other than yes and no, it repeats the option.
stringInput = str(input("Please enter a string: ")) #Asks the user to enter the string.
charactersInput = list(stringInput) #Stores the user input in a list.
print("Your original list is", charactersInput)
print("Your original string: ", stringInput)
stack = []
char_num=3
for ch in stringInput:
if stack and ch != stack[-1][0] and stack[-1][1] >= char_num:
stack.pop()
if not stack or ch != stack[-1][0]:
stack.append([ch, 1])
else:
stack[-1][1] += 1
if stack and stack[-1][1] >= char_num:
stack.pop()
result = ""
while stack:
item = stack.pop()
result = item[0]*item[1] + result
#Output data
print("The output of your string is: ", result,"\n") #Prints the information stored in result. The information does not include the consecutive letters.
if decision == "No" or decision == "no":
print("Thank you for playing! Have a great day!") #The user is shown a goodbye message and the code ends.
exit() #The application ends if the user answers no
Output:-
Hello! Welcome to Candy Crush!
Would you like to add a string? yes
Please enter a string: aaaabbbcccd
Your original list is ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
Your original string: aaaabbbcccd
The output of your string is: d
Other changes i prefer you should do..
(1)No need to check like this if decision == "Yes" or decision == "yes": instead check like if decision.lower()=="yes": same goes for no one also..
Related
Describing the game if you know what means word guessing dont bother to read
Hey! I know I opened a question about that earlier but again Im stuck in another situation. I making a game that there is a list full of words and computer choses a random word in it. And program asking to person guess a letter. If it is in letter it should write the letter in exact order in that word. Lets say our word is word.
If user input is "w", program will print "w___" and again
if user says "o" program will print "wo__" like that.
What is the issue?
I did achieve to print if user input in that word and in which order in that word but when user guess again when he got right in first letter my print variable refreshing and prints just last guessed letter.
Let me explain
My word again "word" and user guess "w" letter first.
So program will print "w___"
But when user guess again and lets say he/she guessed "o" this time.
Program prints just "_.o__" but not w.
What I want to do
Program should keep the last data as "w___" and add "o" letter to second place.
Program should have an if statment and two variables. First is guess_count and other is error_count.
If player guessed right increase guess_count by one and
if guess_count == 5 # word's total letter number: print("Win"), break the loop
If player guessed wrong increase error_count by one and
if error_count == 3 # if player type 3 wrong letter: print("Lose"), break the loop
My code
Create a loop
run = True
while run:
Create a namelist and chose a random name
name_list = ["sound"]
pick_word = random.choice(name_list)
Create a while loop again # whole code is under this
while True:
Get user input
user_input = input("Guess a letter: ")
Creating if statment if for if input len > 1 get error
Whole if true code in there
if len(user_input) == 1:
*Create a variable that gets user input in order of word as number.
(I cant say that sentence in english)
index = pick_word.index(user_input)
Replace the order number to user input
word_tracker[index] = user_input
Create a string to print it
word = "".join(word_tracker)
Print it
print(word)
Increase guess_count
count += 1
If guess_count is 5 break the loop
if count == 5:
If guess not in word
except ValueError:
print("You couldnt guess the letters.")
guessing += 1
if guessing == 3:
print("Peh")
exit()
If guessed letter not 1 character
else:
print("You allowed to type just one letter")
I hope I wont get ban haha
try changing
word_tracker[index] = user_input
to
word_tracker.append(user_input)
That is if 'word_tracker' is a list
Candy Crush horizontal. The program asks for a string and outputs the string remaining after removing groups of 3 or more consecutive identical characters. The removal of the groups continues until no more groups are found to be removed. The program should allow repetition until the user does not want to continue.
#Message
print("Hello! Welcome to Candy Crush!")
while True:
decision = str(input("Would you like to add a string? "))
if decision == "Yes" or decision == "yes":
num = str(input("Please enter a string: "))
list = list(num)
print("Your original list is", list)
print("Your original string: ", num)
while len(list) >= 3:
for i in range(len(list) - 2):
if list[i] == list[i + 1] == list[i + 2]:
list.pop(i + 2)
list.pop(i + 1)
list.pop(i)
print("Your trimmed list is", list)
result = "".join(list)
print("\nThe output of your string is: ", result)
if decision == "No" or decision == "no":
print("Thank you for playing! Have a great day!")
exit()
Traceback (most recent call last):
Python Candy Crush.py", line 12, in <module>
if list[i] == list[i + 1] == list[i + 2]:
IndexError: list index out of range
Hi Dark_Knight and welcome to Stack Overflow!
Here is the solution I had in mind. Although this solves the problem, I wanted to make this a learning experience for you and other programmers who stumble upon this. I blocked off, with comments, the start and end of my changes as well as step by step comments on the decisions I made for the solution.
#Message
print("Hello! Welcome to Candy Crush!")
while True:
decision = str(input("Would you like to add a string? "))
if decision == "Yes" or decision == "yes":
# Start of solution changes
# Lets make variables more clear
stringInput = str(input("Please enter a string: "))
charactersInput = list(stringInput)
print("Your original list is", charactersInput) # Still the same...
print("Your original string: ", stringInput) # Also still the same
# For our loop, idx will be used to track the index of the list
idx = 0
# Lets use a while loop instead of a for loop
# We will exit the loop when there aren't 3 consecutive characters
while idx < len(charactersInput) - 2:
# Check if the current character is the same as the next 2
if charactersInput[idx] == charactersInput[idx + 1] == charactersInput[idx + 2]:
# If so, remove the current and next 2 characters
# We are using pop() to remove the characters
# So the next character will be at the current index
charactersInput.pop(idx)
charactersInput.pop(idx)
charactersInput.pop(idx)
# Okay, we made a change to the list, so we need to reset idx
# As there might be a new set of 3 consecutive characters
idx = 0
else:
# If the current character is not the same as the next two,
# then increment idx by 1
idx += 1
result = "".join(charactersInput)
# End of solution changes
print("\nThe output of your string is: ", result)
if decision == "No" or decision == "no":
print("Thank you for playing! Have a great day!")
exit()
Here are some things to keep in mind that might make finding your own solution easier.
Make sure that all of your variables are clear and don't utilize keywords used in Python (or any other programming language). Using list for a list isn't descriptive and is the same terminology Python uses to work with lists
Break down the problems into smaller pieces. While I was working I first asked "What type of loop do I need?", then "At my current iteration in the loop, what do I need to check?", etc, etc,
Help out the community and include as many fixes you tried before creating a post. It not only helps people trying to help you out but also helps other users learn what solutions don't work
I am writing a simple word guessing game in python. Instead of using a list, I have all the words for the game in a .txt file called as the parameter of a function. The list itself is fine.
The game requires the user to enter a letter. Once the letter is entered, if it matched one of the words that is randomly selected by the random function, it gives points accordingly.
The problem is that when the function runs, the entered letter by the user iterates through all the words in the list. How do I fix this issue?
def guess_game(data):
word = random.choice(data)
print("alright, guess the first letter:")
ans = input("Enter a letter to guess: ")
print(ans)
counter = 0
tries = 15 #how many tries a user is allowed to make
for match in word:
if ans in match:
counter += 10
tries -= 1
print("That's right, 10 points added")
print(f"You have {tries} tries left. ")
elif ans not in match:
counter -= 10
tries -= 1
print("That's wrong, 10 points deducted")
print(f"You have {tries} tries left. ")
few ideas:
make a loop over your "tries" - the player can play until that is 0
the player has to provide the letter inside this loop
check for the letter provided by the player using
if ans in word
Here is my suggestion:
import random
print('Hi, welcome to the guessing game, wanna play?')
answer = input('Enter yes or no: ')
#just added a list to test
data = ['hello', 'coffee', 'tea']
word = random.choice(data)
if answer == "yes".lower():
print("OK, let's play")
print("alright, guess the first letter:")
counter = 0
tries = 15 # how many tries a user is allowed to make
while tries > 0:
ans = input("Enter a letter to guess: ")
print(ans)
if ans in word:
counter += 10
tries -= 1
print("That's right, 10 points added")
print(f"You have {tries} tries left. ")
elif ans not in word:
counter -= 10
tries -= 1
print("That's wrong, 10 points deducted")
print(f"You have {tries} tries left. ")
elif answer == "no".lower():
print("OK, have a good day")
else:
print('Please enter yes or no')
You could also make a list of letter that were already guessed so you can give the player feedback as soon as they found all the needed letters.
Not sure if I understand this completely, but if word is just a word like "apple" or "cat", then your function shouldn't be iterating through your entire list (your list being data). This function iterates through each letter of the randomized word (like "apple") and checks if the inputted letter is equal to any of the letters in that word.
The 'in' keyword itself checks only the first occurrence of a variable in a collection.
However if you want to be more specific, assign your entered word to a variable and then use break keyword after it matches under the if statement while iterating through the list.
Made a list where I want the user to insert x followed by a number. once they have inputted, say x1, I would like x1 to be removed from the list as they are asked to input another number starting with x.
I want the list to be on loop as well, only stopping until one of the groups (of three number) has been chosen.
Disclaimer - I am a beginner at Python + Jupyter Notebook
allwins = (('x1','x2','x3'),
('x4','x5','x6'),
('x7','x8','x9'),
('x1','x4','x7'),
('x2','x5','x8'),
('x3','x6','x9'),
('x1','x5','x9'),
('x7','x5','x3'))
in_item = input("Please enter x followed by a number 1-9: ")
if in_item in allsolutions:
input("Good choice. Now pick another number starting with x: ")
else in_item not in allsolutions:
input("That did not work. Try again: ")
Idk how to keep loop for atleast a few times until the user inputs 3 diff numbers that makes a group.
You can't remove something from a tuple, so you need to make the inner tuples lists.
Then you need to loop over the main tuple, removing the input from each of them if it exists. After you do this you can check if the list is empty.
allwins = (
['x1','x2','x3'],
['x4','x5','x6'],
['x7','x8','x9'],
['x1','x4','x7'],
['x2','x5','x8'],
['x3','x6','x9'],
['x1','x5','x9'],
['x7','x5','x3'])
while True:
in_item = input("Please enter x followed by a number 1-9: ")
item_found = False
solution_found = False
for sublist in allwins:
if in_item in sublist:
sublist.remove(in_item)
item_found = True
if sublist == []:
solution_found = True
if solution_found:
print("You found all of them, congratulations!")
break
elif item_found:
print("Good choice, now pick another")
else:
print("That did not work, now try again")
I've edited my code to the following:
while(True):
#get user to input a noun as a string variable
noun = input()
#get user to input a positive number for the integer variable
number = int(input())
#if the user inputs quit into the string variable stop program
if noun == 'quit':
break
#otherwise print the output
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
And I get the following error codes:
It looks like you edited the code since these answers, this should work
while(True):
noun, number = input().split()
number = int(number)
#if the user inputs quit into the string variable stop program
if noun == 'quit':
break
#otherwise print the output
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
Your problem was that you're calling input twice every loop. So, noun was set to 'apples 5' and number was set to 'shoes 2' which cannot be converted to an integer. You can split the input to get your noun and number.
You should be taking the input inside the loop, otherwise it is an endless loop or if you did write quit then it would just run once. Also there is no need for the == 0 condition to break from the loop according to the problem you have presented.
The problem is that you just take the first input, just get the inputs inside the loop insted.
Also the else should be idented with the if statement and you don't need the number == 0 condition, so the resulting code should be somehting like:
while(True):
#get user to input a noun as a string variable
noun = input()
#get user to input a positive number for the integer variable
number = int(input())
if noun == 'quit':
break
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
Here is how I would write. :)
while True:
noun = input("Enter a noun: ")
if noun == 'quit':
print("Quitting the program...")
break
while True:
number = input("Enter a number: ")
try:
if type(int(number)) == int:
break
except ValueError:
print("Invalid input. Please enter a number.")
if number == '0':
print("Quitting the program...")
break
print("Eating {} {} a day keeps the doctor away.".format(number, noun))