Looping and Lists - BaSe fOO ThE AttAcK Scramble [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
In the war against Skynet, humans are trying to pass messages to each other without the computers realising what's happening.
To do this, they are using a simple code:
They read the words in reverse order They only pay attention to the words in the message that start with an uppercase letter So, something like:
BaSe fOO ThE AttAcK contains the message:
attack the base
However, the computers have captured you and forced you to write a program so they can understand all the human messages (we won't go into what terrible tortures you've undergone). Your program must work as follows:
soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess.
code: soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess.
says: destroy their ice-cream supplies ​
Notice that, as well as extracting the message, we make every word lowercase so it's easier to read.
Could you please help me with my code? This is my code so far:
output=[]
b=0
d=0
code=input("code: ")
code=code.split()
print(code)
a=len(code)
print(a)
while b<a:
c=code[b]
if c.isupper:
output.append(c)
b=b+1
elif c.islower:
b=b+1
else:
b=b+1
print(output)
I need the last line to say "BaSe ThE AttAck" eliminating "fOO" and I will be reversing the string in the last step to make sense, but it is not differentiating between a lowercase word and an uppercase word.

I have rewritten your code.
#code=input("code: ")
code = "soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess"
code=code.split()
output = []
for word in reversed(code): #iterate over the list in reverse
if word[0].isupper(): #check if the FIRST letter (word[0]) is uppercase.
output.append(word.lower()) #append word in lowercase to list.
output = " ".join(output) #join the elements of the list together in a string seperated by a space " "
print(output)
output
destroy their ice-cream supplies

Related

How to remove \ when extract words by python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to implement a function extract_words() that takes in a string of text as its single parameter and returns a list of the words in that string, like this:
input: "There're six words in this string."
output: ["There're", 'six', 'words', 'in', 'this', 'string']
But when I write it like the following and run it in Jupyter Notebook, it shows like this:
I learned how to write this function by the following, so I tried this in Jupyter, and it shows correct:
So may I ask what's wrong with my code, and how to fix it?
The problem is the cast to str inside your function. Just do return inputStr.split() and should works.
def __extract_words__(inputStr):
return inputStr.split()
inputStr = "There're six words in this string."
__extract_words__(inputStr)
There is nothing to replace. Those are escape characters because you returned a string
You want to return the split list as an actual list, not a str() - return inputStr.split()
Look at the docs for the typing module so the type checker would have shown you the issue more clearly. I.e. your function was actually returning a string.
I think what is confusing you is that you needed to use str() when you print the result, but that could be fixed like this
print(f'The list of words is {res}')
That being said, you don't really need your own function if the goal is to only print
test_string = input('text> ')
print(f'The list of words is {test_string.split()}')
Also, the __function_name__ syntax (surrounding underscores) should be reserved for "magic functions" rather than user functions

Python string rearranging [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I am wanting to rearrange strings in python, but don understand what functions would be useful in doing so? Can someone help me understand how do this: remove the first letter of a word and place that letter at the end of the word. Then you append "IE" to the end of the word. I would appreciate it, if someone can link to the functions that might be used, so I can learn how they work.
EDIT: I have tried to make this work with a phrase, but I am having issues with getting it to the ie to go at the end of the words. For example HankTIE ouYIE would be the output of the input Thank You.
Here is what I have:
string = input("Please input a word: ")
def silly_encrypter(string):
words = string.split()
for words in string:
first_letter= words[1:] + words[0]
ie_end = first_letter + "IE"
print (ie_end)
silly_encrypter(string)
As other users pointed out, I strongly suggest you to read Python tutorial, which is very friendly and contains a lot of examples that you can try out in your python console.
Having said that, you could take advantage of string indexing plus concatenation to accomplish the things you want (Both things are mentioned in the tutorial):
remove the first letter of a word and place that letter at the end of the word:
s = "myString"
first_letter_at_the_end = s[1:] + s[0]
# If you print `first_at_the_end` you'll get: 'yStringm'
then append "IE" at the end
ie_at_the_end = first_letter_at_the_end + "IE"
# If you print `ie_at_the_end` you'll get: 'yStringmIE'

How do I shorten my program explained in my body? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am making a simple python project for encrypting messages. Before I share what I want to shorten here is the link to my code for decrypting a message (that I need help with):
https://www.sendspace.com/file/jji74r
My problem is I don't know how to read the message without having to have 25 lines of code, this program tests for 25 characters of encrypted message so if I want to test 30 characters of encrypted text I need 5 more lines of code. Is there any method of decreasing the size of any part of my program?
You could do this with some nested loops -
INCREMENT = 3
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
BEM_LENGTH = 25
#data needed from user to decrypt a message encrypted via BEM
BEM = input("Please input your BEM key: ")
message = input("please input the message you wish to decrypt (up to 26 characters): ")
# processing
for i in range(0, len(message)//INCREMENT):
mess = message[(i*INCREMENT):(i+1)*INCREMENT]
for j in range(0, BEM_LENGTH):
bem = BEM[(j*INCREMENT):(j+1)*INCREMENT]
if mess == bem:
print(ALPHABET[j], end="")
print()
I noticed that the change in the values was always 3, so the INCREMENT I set to 3.
I also needed the alphabet. I put in a BEM_LENGTH constant so that you can easily change it.
After that, I got the input.
Then, I looped through the message, with increments of 3 like you had hardcoded in. Then, I looped through the BEM key and compared it, similar to your if statements. Then, if they were matching, I printed the right character of the alphabet. If you need more help I could email you or chat on discord if you need some help!
I could do this in around 4 lines, using list comprehension, but it would be very difficult to read. This is the most readable, clean way of doing it.

How do I assign a randomly selected letter from a string to a variable in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
First, I would like to say I am new to coding and python in general. I just learned about importing and the random function.
Anyways, I am trying to create a text game, in python, where a letter is chosen randomly from some string/word and the user has to try and guess which letter was chosen. I think I understand how to do for loops well enough so that it continues until the correct letter is chosen, but I have no idea how to even go about randomly choosing the letter.
I would just like some help getting started. Thank you.
Since strings are sequences in Python, you can use random.choice to pick a random element from a list - in your case, a random letter in a string.
>>> import random
>>> c = random.choice("abcdefgh")
>>> c
'g'
>>> c = random.choice("abcdefgh")
>>> c
'a'
The >>>'s are from the REPL console (running Python by itself) and shouldn't be included if you include the code in a python file.
There is a library for randomizing things. Simply use it like this:
import random
text = "Some text"
your_variable = random.choice(text)
and you get your random letter from a sequence in that case which is saved in your_variable.
Since you are relatively new to programming, I'd like to give you an informative example of the game to clarify some concepts.
String str is implemented as sequence in Python (you can think that a string is an array of chars). So it supports indexing s = 'abc'; print(s[1]); shows b.
The standard library random includes a bench of functions to carry out randomized operations. As mentioned in the other answers that the function random.choice randomly pick an element from a sequence. So it can be used to randomly pick a character from a string.
You mentioned loops and you seem to be able to master them. So I hereby use another approach called recursion to continue the game until the desired answer is found.
The game is written in an Object-Oriented manner. If you gonna be a developer latter in your career, it's good practice to see this.
Here is the Code:
import random
class Game:
def __init__(self, string):
self.string = string
def start_game(self):
self.answer = random.choice(string)
self.ask_player()
def ask_player(self):
char = input("Just enter your guess: ")
self.cheat(char)
if char == self.answer:
print("Bingo!")
return None
else:
print("You missed, try again! (Or press Ctrl+C to goddamn exit!)")
self.ask_player()
def show_answer(self):
print('The answer iiiis: %s \n' % self.answer)
def cheat(self, user_input):
if user_input == 'GG':
self.show_answer()
if __name__ == '__main__':
string = "This is the string from which the letters are ramdomly chosen!"
gg = Game(string)
gg.start_game()
Some test runs:
Just enter your guess: 2
You missed, try again! (Or press Ctrl+C to goddamn exit!)
Just enter your guess: T
You missed, try again! (Or press Ctrl+C to goddamn exit!)
Just enter your guess: GG (Haha, I left a cheat code in order to get the right anwser!)
The answer iiiis: o
You missed, try again! (Or press Ctrl+C to goddamn exit!)
Just enter your guess: o
Bingo!

Python Username Generator [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
The following is my code:
string1 = (input("What is your name?")) #creates a string, stores the name in it
first1 = string1[:1]
string2 = (input("What is your last name?"))
first3 = string2[:3]
from random import randint
sentence = "".join((str(randint(0,9)), first1.lower(), first3.upper()))
print (sentence)
sentence = "".join((str(randint(0,9)), first1.lower(), first3.upper()))
print (sentence)
It works, but I am having some trouble. I need to loop this 5 times - but it doesn't work for some reason!
P.S. Python 3!
You are creating a tuple called sentence, rather than a string
If you change that line to this:
sentence = "".join((str(randint(0,9)), first1.lower(), first3.upper()))
It will create a string that has no gaps, like so when printed:
What is your name?First
What is your last name?Last
5fLAS
You are creating a list, not a string so it seems logical that you get issues when trying to print it...
To append to a string you can do that :
sentence = str(randint(0,9))+(first1.lower())+(first3.upper())
In Python, you don't give a type to your variables, it depends of what you put INTO them.
In Python, elements between parenthesis "()" are considered as TUPLE (a type similar to a list, but that cant be modified), "[]" stands for a list, "{}" stands for a dictionnary. So you must NOT put parts of a string between parenthesis and separated with commas or you will turn them into a list of words. Instead you can use "+" that means to Python that you are making a string concatenation. Also note that i casted your random number into string. If you give 3 strings separated by "+" Python will automatically detect sentence as a String. Wp you've created a string !
If you have a list and want to get rid of the spaces you can also use :
"".join(yourlist)
However i don't recommend it here, you would be creating a list and using a join for nothing since you can create a string from the begining.
Edit: As for the loop, we can't answer if you don't copy paste the code of the loop and the error, it could be a million things.

Categories

Resources