str = 'Welcome to the Jungle'
count = 0
for i in str:
if i=='a' or i=='e' not in i=='l' or i=='o' or i=='u':
count += 1
print(count)
Using the precedence order given on https://data-flair.training/blogs/python-operator-precedence/ , == and not in operators have the same precedence so I must go from left to right. According to that logic, since i=='e' evaluates to False for the i=0 that is the first letter W. So, we have False not in i(not in should be evaluated first according to left to right order) which would equate to True for all letters in str except i='e'. But, the python interpreter gives the value of count as 3 which is much less than what should come according to my logic.
Can someone please explain how to solve this problem? This is my first question on StackOverflow, so I apologize if I've written the question in wrong formatting.
Thank You.
#SaumilSood - you have asked how to solve this problem - I will assume you're interested in finding out how many vowels in the sentence in the Pythonic way, if yes, you could try this:
s = 'Welcome to the Jungle'
>>> vowels = 'aeiou'
>>> sum(1 for c in s if c in vowels)
7
Related
I am learning python with a book: The exercise is to make a program that print True if all numbers in a list all odds.
I get it whit this approach
if all(x % 2 == 1 for x in list):
But the 'if all' approach is not yet explained. They only use while, if,for and booleans in the examples. Furthermore, seems to be a reflexive exercise about it is possible to do it, maybe not. It is possible to do it using the basic tools of above?
If you look at the docs: https://docs.python.org/3/library/functions.html#all
all(iterable) .
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
So if all(x % 2 == 1 for x in li): roughly translates to
def are_all_odds(num_list):
#Flag to keep track if we encounter an even number
flag = True
for num in num_list:
#Once we encounter a even number, we break the for loop
if num % 2 != 1:
flag = False
break
#Return the flag
return flag
We can test this function by doing
print(are_all_odds([1, 2, 3, 4]))
#False
print(are_all_odds([1, 3, 5]))
#True
Also just a suggestion, list is a python builtin keyword, so don't use it in variables :)
Yes, it is possible.
The Python code you wrote is very idiomatic, keep up that good work.
To see how to do it differently, you can look at programming languages that are less advanced, such as C. That is a very basic programming language which lacks the features for this if all statement. Searching for "c all elements array true" should give you the code you are looking for. For such a simple piece of code, it's easy to translate the code back into 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 6 years ago.
Improve this question
Can someone possibly tell me what to do with this bit of code?
It always comes back True:
def find_letter(letter, lst):
return any(letter in wordChosen
for wordChosen in attempt)
attempt = input("Enter the letter you think is in the word")
find_letter(attempt, wordChosen)
print find_letter(attempt, wordChosen)`
What's wrong
You don't quite have the idea of the nice command you wrote.
for wordChosen in attempt
iterates your variable wordChosen through every character of the input. The original value is now destroyed.
letter in wordChosen
checks just what you think. However, since you passed in attempt as the value of letter, this must match. Filling in "chosen" for wordChosen and "q" for the attempt, your code is now
find_letter("q", "chosen")
# and the code in the call looks like this:
any(letter in str for str in "q")
This will dutifully take every character in "q" and see whether that character is in the string "q". :-)
Also, please note that you have a useless line of code:
find_letter(attempt, wordChosen)
calls the function and then ignores the return value.
The following line is fine; the print uses the value.
Keep that one and delete the useless one.
The Solution
# find_letter is simple:
def find_letter(letter, lst):
return letter in lst
# Test program
wordChosen = "many_different_letters"
for attempt in "qwertyuiopasdfghjklzxcvbnm":
print attempt, find_letter(attempt, wordChosen)
Output:
q False
w False
e True
r True
t True
y True
u False
i True
o False
p False
a True
s True
d True
f True
g False
h False
j False
k False
l True
z False
x False
c False
v False
b False
n True
m True
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a question. If I have a string, for example:
str1 = 'Wazzup1'
and numbers:
nums = '1234567890'
I need a code that will look into str1 and tell me if it has any number(not all of them). Please help.
Use any and a generator expression:
any(x in nums for x in str1)
Below is a demonstration:
>>> str1 = 'Wazzup1'
>>> nums = '1234567890'
>>> any(x in nums for x in str1)
True
>>>
Note that the above is for when you have a custom set of numbers to test for. However, if you are just looking for digits, then a cleaner approach would be to use str.isdigit:
>>> str1 = 'Wazzup1'
>>> any(x.isdigit() for x in str1)
True
>>>
Use the any function, which returns a Boolean which is true iff at least one of the elements in the iterable is true.
string = 'Wazzup1'
result = any(c.isdigit() for c in string)
print(result) # True
As most Python programmers will tell you, the most concise way to do this is using:
any(x in nums for x in str1)
However, if you're new to Python or need a better grasp of the basics of string manipulation, then you should learn how to do this using more fundamental tools.
You can access the individual elements of a string, list, tuple, or any other iterable in Python using square brackets around an index. The characters of a string are indexed starting from 0 (e.g. "hello"[0] gives "h").
Using a for loop, the solution is easier to understand for a Python newbie than the above-mentioned any solution:
result = False
for i in range(len(str1)):
if str1[i] in nums:
result = True
A Python for loop can also iterate directly over the elements of the string:
result = False
for x in str1:
if x in nums:
result = True
In the first code snippet in this post, the expression x in nums for x in str1 uses Python's list comprehension feature. This goes through every element x of str1 and finds the result of x in nums. any(x in nums for x in str1) returns True if (and only if) at least one of these results is True (meaning a numerical digit is in str1). This is much like the second for loop example given in this post, and many Python programmers choose this option because it is concise and still understandable by other Python programmers.
You can use any() and string.digits to check whether the string contain a digit:
import string
if any(x in string.digits for x in str1):
pass
You could also use a regular expression:
>>> str1 = 'Wazzup1'
>>> import re
>>> bool(re.search(r'\d', str1))
True
Note: there might be a difference in how c.isdigit(), c in nums, int(c) and \d define what is a digit due to locale or Unicode.
Assignment:
Return the number of occurrences of character c in string s,
ignoring case. Use loops. Do not use the in-built string method count,
which does a similar thing. The idea is to learn to write loops. You
should ignore case when comparing a character of s with c.
My attempt:
def countletter(s, c): #BAD
count = 0
for c in s:
if c == c:
count += 1
return count
Am I on the right track? I seem to get some assertion errors when I test it in the main...
your return is at wrong place. So your function is actually returning only after one iteration.
Also you should not use the variable name c in for loop, use some different variable, as it replaces the value of c recieved from the function call with the current character being fetched by the for-loop.
def countletter(s, c): #BAD
count = 0
for x in s:
if x.lower() == c.lower():
count += 1
return count
print countletter("abcdefFf","F") #prints 3
print countletter("a","A") #prints 1
In addition to the answers above, there is a built-in method count in Python. You can use it in your project, if this function isn't a homework etc.(Oh, i saw now, it is an homework. But additional information is harmless.:) )
"baris".count("b")
returns 1
If you compare the variable c defined by for c in s: you are always going to get true. So, your comparison should look like c == 'c' (you can figure out how to do the case insensitive check) and your return is indented incorrectly
The position of the return statement is wrong. Delete the four spaces (or a tab what you've used)
Just as another example of a way to do this outside of the built-in count() method, one can use a generator expression and the sum() builtin:
>>> def countletter(s, c):
... return sum(x.lower() == c.lower() for x in s)
...
>>> countletter("abcdefFf", "F")
3
>>> countletter("a", "A")
1
What we do is produce a generator of True and Falses (True where the character matches). sum() will then give us the count, as True is 1 in Python, and False is 0:
>>> True == 1
True
>>> False == 0
True
This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I'm just getting into Python and I really like the terseness of the syntax. However, is there an easier way of writing an if-then-else statement so it fits on one line?
For example:
if count == N:
count = 0
else:
count = N + 1
Is there a simpler way of writing this? I mean, in Objective-C I would write this as:
count = count == N ? 0 : count + 1;
Is there something similar for Python?
Update
I know that in this instance I can use count == (count + 1) % N.
I'm asking about the general syntax.
That's more specifically a ternary operator expression than an if-then, here's the python syntax
value_when_true if condition else value_when_false
Better Example: (thanks Mr. Burns)
'Yes' if fruit == 'Apple' else 'No'
Now with assignment and contrast with if syntax
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
vs
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True
Moreover, you can still use the "ordinary" if syntax and conflate it into one line with a colon.
if i > 3: print("We are done.")
or
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))
count = 0 if count == N else N+1
- the ternary operator. Although I'd say your solution is more readable than this.
General ternary syntax:
value_true if <test> else value_false
Another way can be:
[value_false, value_true][<test>]
e.g:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. To only evaluate the chosen branch:
[lambda: value_false, lambda: value_true][<test>]()
e.g.:
count = [lambda:0, lambda:N+1][count==N]()
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>
with your code-snippet it would become,
count = 0 if count == N else N + 1