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 3 years ago.
Improve this question
I need to iterate through a string with a mixture of letters and numbers. If it finds at least one number, it returns True, else, it returns false. How can I do this?
You can write a function that returns True when find at least one digit using the isdigit() method.
def has_digit(str):
for letter in str:
if letter.isdigit():
return True
return False
if __name__ == '__main__':
print(has_digit('abcdef'))
print(has_digit('abd5e'))
The output is:
False
True
You can write a function or not as you like. You can also write a ready string or you can use input function:
x = 'Jack77'
for i in x:
if i.isdigit():
print(True)
else:
print(False)
#==================
def checking_digits(x):
for i in x:
if i.isdigit():
return True
return False
print(checking_digits(x))
This will create a list of bool values for each character in the string. isdigit return True if the character is a digit, False otherwise. So if any of the bool values (or any the characters is a digit), it will return True
has_digits = any(i.isdigit() for i in text)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
This code gives exactly what is says but how and why?
To my understanding, for instance the is_odd function if called with any value, the value will diminish into zero and will return True in the is_even() section and so will become False in is_odd() in turn. So every is_odd check supposed to become False but it's not, it just works on every odd/even check, why and how?
#!/bin/python
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_odd(2))
print(is_even(2))
print(is_odd(3))
print(is_even(3))
Output:
False
True
True
False
Note that is_even does not always return True but can also return is_odd(n-1), which in turn return not is_even(n-1), and so on.
Example for is_odd(3):
is_odd(3)
not is_even(3)
not is_odd(2)
not not is_even(2)
not not is_odd(1)
not not not is_even(1)
not not not is_odd(0)
not not not not is_even(0)
not not not not True
not not not False
not not True
not False
True
In general, you get a cascade of N negations for an even number, or N+1 negations for an odd number, and if the number of those negations is even, the result is True.
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 7 months ago.
Improve this question
they need to order with a problem
so I have the text in a certain order of numbers, something like gematria
input [12345] is what we call gematria and what do they need?
they need to line up the digits backwards
[54321]
have a different count and I would need help with that rather than doing twenty different if
def shiftall(s, n):
n %= len(s)
return s[n:] + s[:n]
it didn't help me much it only moves the simple text
For strings:
return s[::-1]
For integers:
return str(s)[::-1]
Note: This would go inside def shiftall(s, n):
Additional note: Now you don't even need the parameter n
If you want to reverse a number, then you can convert it to a string, reverse the string, and then convert it back to a number.
num = 12345
str_num = str(num)
# reverse and convert
num = int(str_num[::-1])
input=[12345,43545436,88888,843546]
def shiftall(s):
d=[]
for i in s:
res=''.join(reversed(str(i)))
d.append(int(res))
return d
print(shiftall(input))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Am learning python and one of the questions in our study guide asks to evaluate RNA sequences. I do not get the expected outputs as suggested by the question, I get 17.
Here is the code:
####START FUNCTION
def rna_length(mrna);
start_rna = 'AUG';
end_rna1 = 'UGA';
end_rna2 = 'UAA';
end_rna3 = 'UAG';
if (mrna[0:3]==start_rna) and (mrna [-3:]==end_rna1 or end_rna2 or end_rna3):
length = len(mrna[3:-3])
return length
else: ((mrna[0:3]!=start_rna) or (mrna [-3:]!=end_rna1 or end_rna2 or end_rna3))
return "Not readable RNA code"
####END FUNCTION
A link to a screenshot of the question here
The issue is you using the boolean operator or to compare strings. You can think of the comparisons like this:
(mrna [-3:]==end_rna1 or end_rna2 or end_rna3)
(((mrna [-3:]==end_rna1) or end_rna2) or end_rna3)
Because or is a boolean operator, it needs to work on booleans. You can convert strings to booleans using bool(<str>)
(((mrna [-3:]==end_rna1) or bool(end_rna2)) or bool(end_rna3))
Any string that is not empty (ie. any string that is not "") is "truthy." What that means is that bool(non_empty_str) == True and bool('') == False.
(((mrna [-3:]==end_rna1) or True) or True)
((True) or True)
(True or True)
True
Now, how should you fix it? There are a few approaches to this.
Properly use or.
if (mrna[0:3]==start_rna) and (mrna[-3:]==end_rna1 or mrna[-3:]==end_rna2 or mrna[-3:]==end_rna3):
length = len(mrna[3:-3])
return length
else:
((mrna[0:3]!=start_rna) or (mrna[-3:]!=end_rna1 or mrna[-3:]!=end_rna2 or mrna[-3:]!=end_rna3))
return "Not readable RNA code"
Use a collection. Note that it is standard to use tuples instead of lists whenever you don't want to modify the collection. I used lists here because the brackets look different. You can also use sets for quicker in, but that's overkill for 3.
if mrna[0:3] == start_rna and mrna[-3:] in [end_rna1, end_rna2, end_rna3]:
length = len(mrna[3:-3])
return length
else:
(mrna[0:3] != start_rna or mrna[-3:] not in [end_rna1, end_rna2, end_rna3])
return "Not readable RNA code"
Heck, you can even use the string methods str.startswith and str.endswith.
if mrna.startswith(start_rna) and mrna.endswith([end_rna1, end_rna2, end_rna3]):
length = len(mrna[3:-3])
return length
else:
...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
def CodelandUsernameValidation(s):
if len(s)>4 and len(s)<25 and s[0].isalpha() and [i for i in s if i.isalnum() or i=="_"]!=[] and s[-1]!="_":
return True
else:
return False
# keep this function call here
print(CodelandUsernameValidation(input()))
It's a list comprehension if you expand, it'll look like this ->
result = []
for i in s: # will fetch element one by one from iterable
if i.isalnum() or i=="_": # checking condition
result.append(i) # if true, then append it to the list
This above code can be rewritten as -
result = [i for i in s if i.isalnum() or i=="_"]
That produces a list of those characters in s that are either alphanumeric or underlines. The code is actually incorrect, because it will pass if ANY of the characters are alphanumeric or underline, whereas the intent surely was that ALL of the characters must be alphanumeric or underline. Here's a better way to write it:
def CodelandUsernameValidation(s):
return 4 < len(s) < 25 and s[0].isalpha() and all(i.isalnum() or i=='_' for i in s) and s[-1] != '_'
print(CodelandUsernameValidation(input()))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Suppose I have a list of strings
['elvis','elo','eels','acdc']
Is there a function that accept this string and returns a unique character for each of the strings? For example, in this case, I expect to get
['e','l','s','a']
Edit: To clarify my meaning.
I want a function that will return an identifier character or string that is based on the input list members. jme answer and bonit's one are a good example.
I think I see your point. There is no built-in for this.
Correct me if I am wrong, but it seems like you want to take the first not already taken character in each string and take one only.
Here is some code to do that
def get_first_not_know(l):
chars = []
for word in l:
for letter in word:
if letter not in chars:
chars.append(letter)
break
return chars
If you don't care about order of letters you take, you can do something quicker using sets.
Assuming BenoƮt Latinier's interpretation of your question is right (which, it looks like it is), then there will be some cases where a unique letter can't be found, and in these cases you might throw an exception:
def unique_chars(words):
taken = set()
uniques = []
for word in words:
for char in word:
if char not in taken:
taken.add(char)
uniques.append(char)
break
else:
raise ValueError("There are no unique letters left!")
return uniques