Counts the Vowels in an input - python-3.4

Instead of showing how many vowels appear in ends up counting them. How can I fix the issue?
def main():
sentence=input("Please type a sentence")
countA=0
for i in sentence:
if i =="a":
countA+=1
print("The letter a appears:", countA,"times")
countE=0
for i in sentence:
if i == "e":
countE+=1
print("The letter e appears:", countE,"times")
countI=0
for i in sentence:
if i == "i":
countI+=1
print("The letter i appears:", countI,"times")
countO=0
for i in sentence:
if i == "o":
countO+=1
print("The letter o appears:", countO,"times")
countU=0
for i in sentence:
if i == "u":
countU+=1
print("The letter u appears:", countU,"times")
countY=0
for i in sentence:
if i == "y":
countY+=1
print("The letter y appears:", countY,"times")
main()

Sentence.count() would be way much easier, but I fixed that for you. Take print commands out of the for loops.
sentence=input("Please type a sentence")
countE=0
for i in sentence:
if i == "e" or i == "E":
countE+=1
print("The letter e appears:", countE,"times")
countI=0
for i in sentence:
if i == "i" or i == "I":
countI+=1
print("The letter i appears:", countI,"times")
countO=0
for i in sentence:
if i == "o" or i == "O":
countO+=1
print("The letter o appears:", countO,"times")
countU=0
for i in sentence:
if i == "u" or i == "U":
countU+=1
print("The letter u appears:", countU,"times")
countY=0
#Or use sentence.count(letter)
#for i in sentence:
# if i == "y" or i == "Y":
# countY+=1
sentence.lower()
print("The letter y appears:", sentence.count("y"),"times")

Related

Diagram evaluation with 3 possible results

Is there a way to check the color of this diagram without using too much if?
Not like this:
if(x == "b" && y == "b"){ return "red";}
if(x == "b" && y == "e1" || x == "b" && y == "e2" .....){ return "green";}
........
I think there must be a way to simple calculate the result with given values for the characters, but I can't find it.
Something like checking x+y=z or x*y=z. Where z can be one of three numbers.
The language doesn't matter.
Thanks
I'd recommend targeting the red diagonal and green column, picking off individual cases and then returning yellow:
if x == "i"{ return "yellow"}
if y == "i"{ return "yellow"}
if x[0] == y[0]{ return "green"}
/*
target remaining green cases
*/
return "yellow"

ParseError: bad input on line 5 [duplicate]

This question already has an answer here:
Python 3.6 quit() not working after porting to exe
(1 answer)
Closed 2 years ago.
score = raw_input("Enter Score: ")
try:
s = float(score)
except:
print "Error"
quit()
if s >= 0.9:
print "A"
elif s >= 0.8:
print "B"
elif s >= 0.7:
print "C"
elif s >= 0.6:
print "D"
else:
print "F"
In place of quit() i recommend you to use sys.exit(0)
import sys
score = raw_input("Enter Score: ")
try:
s = float(score)
except:
print "Error"
sys.exit(0)
if s >= 0.9:
print "A"
elif s >= 0.8:
print "B"
elif s >= 0.7:
print "C"
elif s >= 0.6:
print "D"
else:
print "F"
if you are using python 3 then use parenthesis with print function
** Best Way **
score=input()
try:
s=float(score)
if(s>=0.9):
print("A")
elif(s>=0.8):
print("B")
elif(s>=0.7)
print("C)
except:
print("error")

Can't I use many ifelse in else?

This code is a complex if.
I write this code because I want to use the flow control to decide whether the user can eat the cake or not.
The variables a, b, c, d are some indexes that the user will put in.
In this place, I have already set these indexes.
Based on the indexes, the nested if will give some responses.
a <- 1 ; b <- 2 ; c <- 3 ; d <- 3
index <- sum(a, b, c, d)
if(index > 11){print("enjoy the cake right now!")
}else{
if(b == 1 | c == 1){"You don't have the right to eat cake."
}else{
ifelse(b == 3, "go to ATM and take money right now",
ifelse(b == 2, "use the budget of tomorrow first",print("") )
)
print("bb")
ifelse(c == 4, "run to the cake store and burn some calores ",
ifelse(c == 3,"ride youbike to the cake store",
ifelse(c == 2, "ride youbike to the cake store",print(""))))
print("aa")
}
}
My expectation is:
[1] "use the budget of tomorrow first"
[1] "bb"
[1] "ride youbike to the cake store"
[1] "aa"
But the result is:
[1] "bb"
[1] "aa"
Why the R program didn't run the "ifelse" part and just printed "bb", "aa"?
Is this because the "else" can't include "ifelse"?
You can have multiple ifelse in else but it doesn't print the string here is because ifelse returns the value and does not print them by default. You need to explicitly print them. If you add print around those strings in ifelse it would work. However, as you have scalar input to compare here you can use if/else instead of ifelse which is usually used for vector inputs.
if(index > 11) {
print("enjoy the cake right now!")
} else {
if(b == 1 | c == 1) {print("You don't have the right to eat cake.")
} else{
if(b == 3) print("go to ATM and take money right now")
else if(b == 2) print("use the budget of tomorrow first") else print("")
print("bb")
if(c == 4) print("run to the cake store and burn some calores ")
else if (c == 3) print("ride youbike to the cake store")
else if(c == 2) print("ride youbike to the cake store") else print("")
print("aa")
}
}
#[1] "use the budget of tomorrow first"
#[1] "bb"
#[1] "ride youbike to the cake store"
#[1] "aa"

Latex expression replacement in R

I'm working with a LaTex document in R and I need to change {#1 \over #2} to \frac{#1}{#2}.
With simple expressions like:
{1\over 2}
{x^2+y^2\over \lambda}
I can do it with stringr::str_replace() or gsub base functions and the regex \\{([\\^a-z0-9\\\\\\s\\+\\-\\*/\(\)]+)\\s*\\\\over\\s*([\\^a-z0-9\\\\\\s\\+\\-\\*/\(\)]+)\\} (I guess there has to be a better approach to do this. I tried with \\{(.+)\\s*\\\\over\\s*(.*)\\} but it captured more than I wanted.)
But when I work with expressions like:
{e^{2c} \over x-1}
{2yz\over 1+x^{2} }
or a more complicated expression:
\\item $Dom\\left(Q\\right)\\ne {\\rm R}^{2} $ y uno de los puntos no pertenecientes al dominio es $\\left({1\\over 2} ,{1\\over 2} \right).$
the above regex failed.
Is there a regex that can catch all the alternatives? Thanks
Given some sample strings:
> strings
[1] "{1\\over 2}" "{x^2+y^2\\over \\lambda}"
This monster:
> unlist(
lapply(
strsplit(
sub("\\}$","",
sub("^\\{","",strings)),"\\\\over"),
function(x){paste0("\\frac{",x[1],"}{",x[2],"}")}))
produces:
[1] "\\frac{1}{ 2}" "\\frac{x^2+y^2}{ \\lambda}"
This will break if there's more than one \over in the source string. And probably in many other cases too... Oh, it doesn't work if there's spaces before the first { or after the closing }.
On your other examples you get this:
in out
[1,] "{1\\over 2}" "\\frac{1}{ 2}"
[2,] "{x^2+y^2\\over \\lambda}" "\\frac{x^2+y^2}{ \\lambda}"
[3,] "{e^{2c} \\over x-1}" "\\frac{e^{2c} }{ x-1}"
[4,] "{2yz\\over 1+x^{2} }" "\\frac{2yz}{ 1+x^{2} }"
I rather enjoyed this question.
At some point you have to parse the document. parse_tex from TeXCheckR had LaTeX not plain TeX in mind but seems to do okay here. For multi-line instances of \over the script would need to be changed though the principle would be the same I think.
The challenge was for continued fractions.
library(data.table) # for shift
library(TeXCheckR) # for parse_tex
locate_over <- function(doc_parsed) {
lead <- function(x, n) data.table::shift(x, n = n, type = "lead", fill = "")
char <- .subset2(doc_parsed, "char")
which(char == "\\" &
lead(char == "o", 1L) &
lead(char == "v", 2L) &
lead(char == "e", 3L) &
lead(char == "r", 4L))
}
over2frac <- function(lines, verbose = FALSE) {
out <- lines
for (i in seq_along(lines)) {
if (grepl("\\over", lines[i], fixed = TRUE)) {
i_parsed <- parse_tex(lines[i])
# Find lhs
for (j in locate_over(i_parsed)) {
lhs_start <- max(which(.subset2(i_parsed, "char") %chin% c("$", "{") &
.subset2(i_parsed, "column") < j &
.subset2(i_parsed, "tex_group") == .subset2(i_parsed[j], "tex_group")))
rhs_end <- min(which(.subset2(i_parsed, "char") %chin% c("$", "}") &
.subset2(i_parsed, "column") > j + 4L &
.subset2(i_parsed, "tex_group") == .subset2(i_parsed[j], "tex_group")))
i_parsed[lhs_start, char := "{\\frac{"]
i_parsed[rhs_end, char := "}}"]
}
res <- paste0(i_parsed[["char"]], collapse = "")
res <- gsub("\\over", "}{", res, fixed = TRUE)
out[i] <- res
}
}
out
}
Test TeX document:
$5 \over 2$
This is another fraction: ${1 \over 2}$.
And another:
$$A = a \over b$$
What about:
$${{D \over C} \over H}$$
Finally:
$${e^{2c} \over x-1}$$
${2yz\over 1+x^{2} }$
$$\phi = 1 + {1 \over {1 + {1 \over {1 + {1 \over {1 + \ddots}}}}}}$$
\item $Dom\left(Q\right)\ne {\rm R}^{2} $ y uno de los puntos no pertenecientes al dominio es $\left({1\over 2} ,{1\over 2}\right).$
\bye
Resulting LaTeX document: with the necessary LaTeX-specific stuff, plus mandatory math mode for inline fractions. writeLines(over2frac(readLines("tex1.tex"), verbose = FALSE), "latex1.tex")
\documentclass{article}
\begin{document}
${\frac{5 }{ 2}}$
This is another fraction: ${\frac{1 }{ 2}}$.
And another:
${\frac{A = a }{ b}}$
What about:
$${\frac{{\frac{D }{ C}} }{ H}}$$
Finally:
$${\frac{e^{2c} }{ x-1}}$$
${\frac{2yz}{ 1+x^{2} }}$
$$\phi = 1 + {\frac{1 }{ {1 + {\frac{1 }{ {1 + {\frac{1 }{ {1 + \ddots}}}}}}}}}$$
\item $Dom\left(Q\right)\ne {\rm R}^{2} $ y uno de los puntos no pertenecientes al dominio es $\left({\frac{1}{ 2}} ,{\frac{1}{ 2}} \right).$
\end{document}
This gets you most of the way for your examples:
library(stringr)
s <- "Expression 1 is {1\\over 2}.
Expression 2 is {x^2+y^2\\over \\lambda}, yes it is.
Expression 3 is {e^{2c} \\over x-1}.
The last expression: {2yz\\over 1+x^{2} }, all done now."
s2 <- str_replace_all(s,
"\\{(.*?)\\s{0,}\\\\over\\s{0,}(.*?)\\}",
"\\frac\\{\\1\\}\\{\\2\\}")
s2
[1] "Expression 1 is frac{1}{2}.\n\nExpression 2 is frac{x^2+y^2}{\\lambda}, yes it is.\n\nExpression 3 is frac{e^{2c}}{x-1}.\n\nThe last expression: frac{2yz}{1+x^{2} }, all done now."
The only issue is that a space remains in the last expression, which may not be a problem since it existed in the original:
frac{2yz}{1+x^{2} }
x=c("{e^{2c} \\over x-1}","{2yz\\over 1+x^{2} },,dty{k^4e{-rpi/3}\\over\\sqrt{2pik}}")
gsub("\\{(.*?)\\\\over(.*?)\\}","\\\frac{\\1}{\\2}",x)
[1] "\frac{e^{2c} }{ x-1}"
[2] "\frac{2yz}{ 1+x^{2} },,dty\frac{k^4e{-rpi/3}}{\\sqrt{2pik}}"
Explanation:
\{(.*?)\\over(.*?)\\
List item{ matches the character { literally (case sensitive)
1st Capturing Group (.*?)
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
\\ matches the
character \ literally (case sensitive) over matches the characters
over literally (case sensitive)
2nd Capturing Group (.*?)
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
\\ matches the character \ literally (case sensitive)
This approach can handle:
multiple {...} containing \over on the same line
{...} not containing \over
other text before, after and between occurrences of {...}
lines not having any {...} with \over
For example, note in the example below the {jjj} on the second input line before the first occurrence of a {...} with \over works as expected.
It makes use of gsubfn which can handle balanced parentheses. First create a proto object p similar to the one in my answer here. p initializes a counter k to 0 and increments it for each { and decrements it for each }. It replaces any { for which k=1 with ! and also any } for which k=0 with !.
Then replace !...\over...! with \frac{...}{...} and replace any remaining !...! with {...}.
We have assumed that ! does not appear in the input but if it does choose a different character.
library(gsubfn)
library(magrittr)
# test input
s <- c("abc {1\\over 2} def {x^2+y^2\\over \\lambda} ghi { 12 } XYZ",
"X {jjj} A {e^{2c} \\over x-1} jkl {2yz\\over 1+x^{2} } Z")
# processing
p <- proto(
pre = function(.) .$k <- 0,
fun = function(., x) {
if (x == "{") .$k <- .$k + 1 else if (x == "}") .$k <- .$k - 1
if (x == "{" && .$k == 1) "!" else if (x == "}" && .$k == 0) "!" else x
})
s %>%
gsubfn("[{}]", p, .) %>%
gsub("!([^!]*)\\\\over ([^!]*)!", "\\\\frac{\\1}{\\2}", .) %>%
gsub("!([^!]*)!", "{\\1}", .)
giving this result:
[1] "abc \\frac{1}{2} def \\frac{x^2+y^2}{\\lambda} ghi { 12 } XYZ"
[2] "X {jjj} A \\frac{e^{2c} }{x-1} jkl \\frac{2yz}{1+x^{2} } Z"

Converting user input to a number

It might be a silly mistake but I'm not able to figure it out.
Here's the sample:
if(K<=50 & k<=K) {
cat("Message A", "\n")
} else {
if(K>50) {
cat("Error A","\n")
return(0)
} else {
cat("Error B","\n")
return(0)
}
}
If I enter K = 9 and k = 2, I still get Error A and the program stops.
Why?
EDIT:
If I take user input for K and k, it gives the "Error A" message. "Error B" works fine. I never get "Message A"
K<-readline("Enter K: ")
k<-readline("Enter k: ")
The reason you're seeing this error is that the readline function returns a string instead of a number. When R compares between a string and a number, it will convert both to a string and compare them alphabetically:
"9" <= 50
# [1] FALSE
"1" <= 50
# [1] TRUE
The solution is to convert the inputted values to the numeric type:
K <- as.numeric(readline("Enter K: "))
k <- as.numeric(readline("Enter k: "))
Note that if you enter something that's not a number then R will store that value as NA; you can check for this with the is.na function.

Resources