I'm new to python. I've recently begun playing around with the concepts to try and expand my understanding and application. I tried a simple problem being "count the vowels in a string". I was able to solve it however, i was looking at other people's code and found this:
def vowel_count (string):
find_vowel = 0
for letter in string.lower():
if letter in "aeiou":
find_vowel += 1
return find_vowel
Can anyone break down this code line by line for me please.
I'm especially a bit disoriented with understanding the concept of starting off with find_vowel = 0 and the part where is has find_vowel +=1. I interpreted this as find_vowel being assigned a new value of 1 as it was added to the previous value of zero, but i'm not sure exactly how it is connected or counts the vowels exactly. I ran the code though and it works so I'd just like to know the finer details behind it.
Thanks in advance!
If you're asking what += means, then I can tell you that.
+= is an operator that adds to a variable. It increments a variable by any amount, and it is a very helpful shortcut.
Say you have a variable called money.
To add to money, you could do this:
money = money + 1
A shorcut to that would be:
money += 1
Hopefully this helps!
An implementation with better variable naming would be this:
def count_vowels(string):
count = 0
for letter in string.lower():
if letter in "aeiou":
count += 1
return count
The += operator increments, or adds 1 to, the count value. Every time a vowel is found, the value of count increases by 1, representing the presence of that vowel in the string.
Related
I'm working on a small personal project where I turn a d&d story into a game.
I ran into a problem when the story reaches a point where a sheep runs to the character with the highest magic , and since I generate magic randomly at the start of the session , sometimes two characters can have the same magic value so I give it to the character with the highest charisma between the ones with the highest magic .. since I'm a beginner I tried to solve this with lists, a solution with dictionaries would be much appreciated but that's not my question, I came up with a solution that seems logical to my nooby eyes but if more than one character have equal charisma(regardless of magic values) the code fails and chooses randomly.
here is the code , what would be very useful is if I knew where the code bugs and why
since its completely invisible to me .
`
magic=[]
charisma=[]
ttt=["Khablan","Gadaan","El-Armoty" ,"Kulayb",'Zaafaran']
def attributeassigner(ww):
for x in ttt:
ww.append(random.randrange(1, 10))
return ww
print(attributeassigner(magic))
print(attributeassigner(charisma))
def maxfinderassigner(ba):
o=[k for k,x in enumerate(ba) if x == max(ba)]
return o
def anychooser(dodo):
e=ttt[dodo.index(max(dodo[t]for t in maxfinderassigner(magic)))]
return e
print(anychooser(charisma))
`
The expression
max(dodo[t]for t in maxfinderassigner(magic))
computes the maximal charisma among characters with maximal magic. Then, however, you are searching for a character with this maximal charisma in a list of all characters - not necessarily the ones with maximal magic.
This should fix the problem. It'll first check if there is someone with the highest magic. Then, it will check for someone with the highest charisma. If there are characters with the same amount of both, Tie will be returned.
import random
magic = []
charisma = []
ttt = ["Khablan","Gadaan","El-Armoty" ,"Kulayb",'Zaafaran']
def attributeassigner(ww):
for x in ttt:
ww.append(random.randrange(1, 10))
return ww
print(attributeassigner(magic))
print(attributeassigner(charisma))
def anychooser():
if magic.count(max(magic)) == 1:
return ttt[magic.index(max(magic))]
if charisma.count(max(charisma)) == 1:
return ttt[charisma.index(max(magic))]
return "Tie"
print(anychooser())
I have been following a book for learning python, and the book has one of the following challenge:
Self Check
Here’s a self check that really covers everything so far. You may have
heard of the infinite monkey theorem? The theorem states that a monkey
hitting keys at random on a typewriter keyboard for an infinite amount
of time will almost surely type a given text, such as the complete
works of William Shakespeare. Well, suppose we replace a monkey with a
Python function. How long do you think it would take for a Python
function to generate just one sentence of Shakespeare? The sentence
we’ll shoot for is: “methinks it is like a weasel”
You’re not going to want to run this one in the browser, so fire up
your favorite Python IDE. The way we’ll simulate this is to write a
function that generates a string that is 28 characters long by
choosing random letters from the 26 letters in the alphabet plus the
space. We’ll write another function that will score each generated
string by comparing the randomly generated string to the goal.
A third function will repeatedly call generate and score, then if 100%
of the letters are correct we are done. If the letters are not correct
then we will generate a whole new string.To make it easier to follow
your program’s progress this third function should print out the best
string generated so far and its score every 1000 tries.
I was able to implement this part of the challenge, with the following code:
(I am new to python)
import random
target = 'methinks it is like a weasel'
target_len = 28
def string_generate(strlen):
alphabet = 'abcdefghijklmnopqrstuvwxyz ' #26 letters of the alphabet + space
res = ''
for i in range(strlen):
res += alphabet[random.randrange(27)]
return res
def score_check(target,strlen):
score = 0
res = string_generate(strlen)
for i in range(strlen):
if res[i] == target[i]:
score += 1
return score, res
def progress_check():
counter = 0
score = 0
res = ''
while score != 28:
score_temp, res_temp = score_check(target, target_len)
counter += 1
if score_temp > score:
score, res = score_temp, res_temp
print(res, score)
else:
score, res = score, res
return res, score
progress_check()
It then have the following extra challenge:
Self Check Challenge
See if you can improve upon the program in the self check by keeping
letters that are correct and only modifying one character in the best
string so far. This is a type of algorithm in the class of ‘hill
climbing’ algorithms, that is we only keep the result if it is better
than the previous one.
However, I am not able to figure out what this hill climbing algorithim is, and how I would implement it into my existing piece of code.
Please explain how to implement this hill climbing algorithm, thank you all so much!
I am working with the code that would read the input of the strings and compute whether the parenthesis (using arbitrary characters for open and close) are balanced. The aim is to prompt user to input the amount of brackets as strings, so the compiler would compute their amount and type(ex. if it is '(' or ')') .
I have been given hints:
Hint1: introduce two counters initialized to zero in the beginning.
Then explore the symbols of the string in a loop. For the current
symbol increment the left counter by 1 if the symbol is '(',
otherwise, increment by 1 the `right' counter
Hint2: call a string math-like if the brackets occur like in a
mathematical formula. For instance, the strings '()', '(())()',
'(()())' are balanced, while the strings '))(())((' and '())(()'
are not.
My code now looks like this:
lefts =str(input("Please enter a left parenthesis: "))
rights =str(input("Please enter a right parenthesis: "))
#token parsing requires paying attention to the order of the parenthesis
def ptest(test): #testing with counters
lefts = 0
rights = 0
balance = 0 #additional counter that will help us determine the amount of strings and their relation to each other
for c in test:
if c == '(':
balance += 1
lefts += 1
elif c == ')':
balance -= 1
rights += 1
print ('testing "'+test+'"')
print ('lefts='+str(lefts)+' rights='+str(rights))
#if there will b a balance between the strings/parenthesis, they will possibly be balanced
if balance == 0: print 'same number of open/close, possibly balanced'
else: print 'different number of open/close, definitely not balanced'
ptest(test1)
ptest(test2)
How could I modify this in order that it would work?
But I think you partly misunderstood the task.
There can be many brackets, but no more ")" than "(" (and at the end the number of both types must be equal)
And I would think, that the input not only consists of brackets
So you should build a loop (as you did) and
test, whether the char is a bracket or not
if a bracket, so increase the matching counter (you could even have one Counter, but it is easier to understand with two of them
Check, whether the closing Counter is smaller than the opening (if not, so you could break the Loop, cause it is not mathematical)
After the end of the loop you must check, whether there were an error in the Loop or both Counters are not equal. In both cases the string is not "mathematical", otherwise it is.
I could do it in your code, but I think, you should do THIS alone. Most of These things you have already done, but it seems as you did not completly understand, what you have done and have to do.
I am in intro programming class and I just started learning the loops. My question asks about the average value of the inputs and it supposed to be done with while-loops. When the user inputs end instead of a number, that signifies the end of the loop and calculates the average value. The program should print the average value and return it. Also, if the user does not input any number and directly inputs end, the program should print "No numbers were entered". I tried creating the loop, but I do not know what I am missing for my loop to be running.
Also, I am not allowed to use any inbuilt functions like sum, ave, etc.
Here is the code I've written so far
def avgOfTheSum():
total = 0
avg = 0
count = 0
while True:
number = input("Enter next number:")
if number != 'end':
num = float(number)
total = total + num
count = count + 1
average = total/count
else:
print("The Average is:",average)
break
return average
a few tips from my not-so-experienced point of view :
when you increment a variable, eg. 'total = total + num', you can do so with a more compact way : use 'total += num' which does exactly the same thing and lightens your code. Some people find it ugly though, so use it if you will.
You first declared a variable named 'avg' but you then later use 'average', which leads to an error when trying to print 'average' which was not defined because the first 'if' statement was bypassed.
You should use one naming for the average. Either 'avg' or 'average' is okay but remember your code must be easy to understand so try not to squeeze things too much, especially if someone is reviewing it when you are finished.
Use one name and stick to it. That way you don't have an error when the user inputs something that isnt handled by your code.
You could add safe nets to ensure the user passes a number but the most simple ways need to use python built-ins.
You could add something like (not python do not write it like so)
if count = 0
then print 'no numbers entered'
then either :
break if you want to quit the application
or pass if you want to force the user to enter a number (enforcing a new loop)
Hope it helped you a little bit !
I'm trying to solve this problem:
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000
digits?
check = True
mylst = [1,1]
i = 1
while check:
if len(str(mylst[i])) >= 1000:
check = False
else:
mylst.append(mylst[i-1] + mylst[i-2])
i=i+1
a =str((mylst[len(mylst)-1]))
print(len(a))
print(a)
I seem to get correct answer for test cases 2 and 3 but my answer is not being accepted. Please help me me I am not able to understand what went wrong.
I think you have an error in your code. If you look at the first iteration, you start with i=1 then call
mylst.append(mylst[i-1] + mylst[i-2])
Which will add mylst[0] + mylst[-1]. This also gives me incorrect answers (for finding the first index with 3 digits, F12. Your code gives me F18).
Obviously this is not what you want to do. You can fix it by changing the list indices you are adding together.
check = True
mylst = [1,1]
i = 1
while check:
if len(str(mylst[i])) >= 1000:
check = False
else:
mylst.append(mylst[i] + mylst[i-1])
i=i+1
Then, as others have mentioned, you want the index of the answer.
print len(mylst)
The answer is the index of the fibonacci number, not the number itself.
So, if Fn is the first term in the Fibonacci sequence to contain 1000 digits you need to enter the corresponding n.
Because the question is what term is the first to contain 1000 digits, not which number. So, if the question was
What is the first term in the Fibonacci sequence to contain 3 digits?
The answer would have been 12, not 144.
A general tip on Project Euler: Read the problem description carefully. And do it at least 3 times. If I had burned one calorie for each minute I've spent troubleshooting a PE problem due to a misread of the problem text, my body would probably be in a healthy shape.