Looping and Lists - BaSe fOO ThE AttAcK - python

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

Here's My answer, Tested on grok learning and green across the board:
code = input('code: ')
code=code.split()
output = []
for word in reversed(code):
if word[0].isupper():
output.append(word.lower())
output = " ".join(output)
print('says:', output)

There are two issues with your code:
isupper and islower are methods, i.e. you need to call them by writing ().
c.isupper() will check if the entire word is upper-case. However, your problem description says to just consider the first character of each word. Hence, try using c[0].isupper().
Now, after that has been fixed, you're still left with reversing the output list (and making each word lowercase) but I suppose you didn't get to that just yet. :-)

Related

Python - Finding all uppercase letters in string

im a really beginner with python and I'm trying to modify codes that I have seen in lessons.I have tried the find all uppercase letters in string.But the problem is it only gives me one uppercase letter in string even there is more than one.
def finding_upppercase_itterative(string_input):
for i in range(len(string_input)):
if string_input[i].isupper:
return string_input[i]
return "No uppercases found"
How should i modify this code to give me all uppercase letters in given string. If someone can explain me with the logic behind I would be glad.
Thank You!
Edit 1: Thank to S3DEV i have misstyped the binary search algorithm.
If you are looking for only small changes that make your code work, one way is to use a generator function, using the yield keyword:
def finding_upppercase_itterative(string_input):
for i in range(len(string_input)):
if string_input[i].isupper():
yield string_input[i]
print(list(finding_upppercase_itterative('test THINGy')))
If you just print finding_upppercase_itterative('test THINGy'), it shows a generator object, so you need to convert it to a list in order to view the results.
For more about generators, see here: https://wiki.python.org/moin/Generators
This is the fixed code written out with a lot of detail to each step. There are some other answers with more complicated/'pythonic' ways to do the same thing.
def finding_upppercase_itterative(string_input):
uppercase = []
for i in range(len(string_input)):
if string_input[i].isupper():
uppercase.append(string_input[i])
if(len(uppercase) > 0):
return "".join(uppercase)
else:
return "No uppercases found"
# Try the function
test_string = input("Enter a string to get the uppercase letters from: ")
uppercase_letters = finding_upppercase_itterative(test_string)
print(uppercase_letters)
Here's the explanation:
create a function that takes string_input as a parameter
create an empty list called uppercase
loop through every character in string_input
[in the loop] if it is an uppercase letter, add it to the uppercase list
[out of the loop] if the length of the uppercase list is more than 0
[in the if] return the list characters all joined together with nothing as the separator ("")
[in the else] otherwise, return "No uppercases found"
[out of the function] get a test_string and store it in a variable
get the uppercase_letters from test_string
print the uppercase_letters to the user
There are shorter (and more complex) ways to do this, but this is just a way that is easier for beginners to understand.
Also: you may want to fix your spelling, because it makes code harder to read and understand, and also makes it more difficult to type the name of that misspelled identifier. For example, upppercase and itterative should be uppercase and iterative.
Something simple like this would work:
s = "My Word"
s = ''.join(ch for ch in s if ch.isupper())
return(s)
Inverse idea behind other StackOverflow question: Removing capital letters from a python string
The return statement in a function will stop the function from executing. When it finds an uppercase letter, it will see the return statement and stop.
One way to do this is to append letters to list and return them at the end:
def finding_uppercase_iterative(string_input):
letters = []
for i in range(len(string_input)):
if string_input[i].isupper():
letters.append(string_input[i])
if letters:
return letters
return "No uppercases found"

function for word frequency + dictionary

I am trying to create a function to take in a string and return how many times a word in it has been used (with the word) as a dictionary. I also want it to look for a specific list of words to search up the string when provided and return the frequency of the words in the given list found in the string.
Example,
stringfunc = "I went to school today, to learn!"
print(wordfunc(stringfunc))
should return
{'i':1 , 'went':1, 'to':2, 'school':1, 'today':1, 'learn':1}
And,
stringfunc = "I went to school today, to learn!"
print(wordfunc(stringfunc,wordlist=["I", "feel", "Great"]))
should return
{'i':1, 'feel':0, 'great':0}
This is what I have so far
def wordfunc(stringfunc,wordlist=[]):
count_dict = dict()
stringfunc=stringfunc.lower() # i want it to be case insensitive
word = stringfunc.split()
for i in range(len(word)):
x = ord(word[i][-1]) # in the next few lines I am trying to get rid of special characters
if (not(x>=97 and x<=112) or (x>=65 and x<= 90)):
word[i]=word[i][:-1] # if a word ends with , or ! i want it to discount last character
for i in wordlist:
if (i not in word):
count_dict[i]=0
else:
count_dict[i]=word.count(i)
return count_dict
When I try
stringfunc = "I went to school today, to learn!"
print(wordfunc(stringfunc,wordlist=["I", "feel", "Great"]))
I get
{'I':1, 'feel':0, 'Great':0} # i can't get a lower case i don't know why
and when I try
stringfunc = "I went to school today, to learn!"
print(wordfunc(stringfunc))
I get an empty dictionary {}
Can you help me identify my error? Thanks!
You "can't get lower case" because you didn't program it. If the input supplies wordlist, then you blithely accept whatever is there. In the given case, you have two words capitalized, so that's what comes out. Instead, you need to convert every element of wordlist to lower case, just as you did with the input string.
BTW, do not give misleading names to variables: stringfunc is not a function.
The main loop will be much easier to read if you quit playing games with ASCII code values. Instead, simply use isletter. If this is new to you, then I strongly recommend that you repeat your tutorial on string processing; you missed some useful things that you will now recognize.
That said, also look up the collections package, notably the Counter type. Once you've cleaned out all but letters and spaces in your input string, you can do the main processing with
count_dict = Counter(stringfunc.split())

Python guessing word game

I trying to convert my code using function. As this coding is not done yet but i manage to get the code running well. The only thing is every time i guess a letter, it reset my previous record. How to i store my previous guess result and continue add if the letter is guessed correctly?
import random
def chooseAword(wordList):
correct_word = random.choice(wordList)
return correct_word
#def spelltheword(word)
def guessAletter(guessedletter):
word = guessedletter
guess = input('Guess a letter: ')
letter = ''.join(x if x in guess else '-' for x in word)
if guess in word:
print("So far you have: ", letter)
else:
print("So far you have: ", letter)
return letter
def playAgame(wordList):
word = chooseAword(wordList)
for n in range(5):
guessletter = guessAletter(word)
def main():
wordList = ('python', 'csharp','java','oracle')
playAgame(wordList)
main()
No, it doesn't reset your previous record: you have no previous record. Every call to guessAletter very specifically puts a hyphen in any position that is not the currently guessed letter.
Yes, you return the word (which you named letter, for some reason) of hyphens and correct letters, but the calling program playAgame puts this into a local variable guessletter (another misleading name), and then never uses it again.
I have several suggestions:
Practice incremental programming. Write a few lines of code to perform a trivial part of your program. Debug them. Do not continue until you know they do what you want, through testing several possibilities. Then write a few more lines; repeat this process until your program works.
Use meaningful variable names. word doesn't tell us much; we don't know whether this is the word we're supposed to guess, the current game progress you show the user, or something else. At the worst, you use guessedLetter for something that is not a single letter, and is not a guess.
With the incremental programming, follow the status of your game state: this should be one value passed back and forth with your guess-and-check function. You update it in that function, and print it in the guess-a-letter loop.

Checking if the first character of an input is a vowel doesn't work

I'm trying to make a program deciding what determiner comes behind the input.
#For now, this only works with letters A-D.
MyInput = input("What word do you want to find out if the determiner is a/an?")
Finder = list(MyInput)
if ('a' in Finder):
print ("Start with an.")
else:
print ("Start with a.")
However, there is a little bug. When I input the word "bad", it says I need to have "an" go before the word. I want it to only say I need to have "an" be before the word when the first letter is A. What's the solution to this problem?
It is because in checks if the character can be found anywhere in the string. When you use "bad" it can. If you are checking the first character use Finder[0]
MyInput = input("What word do you want to find out if the determiner is a/an?")
Finder = list(MyInput)
if (Finder[0].lower() == 'a'):
print ("Start with an.")
else:
print ("Start with a.")
Regarding the question, using str.startwith would be the most clear way to go:
# For now, this only works with letters A-D.
my_input = input("What word do you want to find out if the determiner is a/an?")
if my_input.startswith('a'):
print ("Start with an.")
else:
print ("Start with a.")
Pay attention to the fact you do not need to make a list from a string: strings are iterable, they support in and indexing out of the box.
Also note the readability improvements:
Name variables using snake_case
Start a comment with a space
Do not put a conditional into brackets
See PEP8, the python style guide for more issues and details about codestyle.
Cheers!

Count Occurrences using for, in, and return

I have been trying to write the code for this program for a while now, but I just cannot figure it out. I am very confused. I would appreciate the help:
Write a function that takes two strings. The second string should only be one character long. The function should return how many times the second string occurs in the first string.
You will need:
A function declaration, with parameters.
A for loop.
An if statement.
A return statement.
What I have so far:
string_one = "I love coding!"
string_two = "I"
if string_two in string_one: print "Hi"
Considering the code you have provided, it indeed works if string_two is in string_one, meaning that your if-condition is correct. However, it will only run once, so if string_two occurs multiple times in string_one, it will ignore all other occurences and print Hi only once. As a result, you need to add your if-condition into a for-loop to catch all occurences of string_two in string_one.
string_one = "I love coding!"
string_two = "o" # changed to 'o' since it has more than 1 occurence in string_one
for letter in string_one: # look at each letter in string_one, one after another
if string_two in letter: # also possible: if string_two == letter
print "Hi" # print Hi when the letter is found
All that's left to do now according to your task is to wrap this code into a function with two parameters (ideally one parameter called sentence and another one called character or similar) and return something. However, I will leave figuring this out to yourself, good luck! :)
First off, let's note that this problem could be solved using str.count(thing_to_count). That's what you should use in general, but I see here you are probably asking for help on an assignement (generally discouraged on Stack Overflow, but I personally don't have an issue with it). Anyway, here's the code I made for this.
def count_in_string (sentence, thing_to_count):
times = 0
for word in sentence:
for letter in word:
if letter == thing_to_count: times += 1
return times
So:
Declare count_in_string as a function with the arguments sentence and thing_to_count.
Set times to be the amount of times thing_to_count_ appears in sentence (so far 0).
Loop through every word, and then letter in the sentence.
See if the letter is the thing_to_count, and if so add 1 to times.
Return times as the result.

Categories