Creating a function to do what the builtin function "isdigit" does [closed] - python

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
def my_isdigit(str):
if digit in str >0 and str is int:
print "True"
else:
print "False"
I am trying to create a function that does what isdigit does i.e. returns true if all characters in the string are digits and there is at least one character, false otherwise. Every time I try to use this it tells me "digit" is not defined. I am confused as to what it is asking me to change... Help would be greatly appreciated!

The function looks at each character and only returns True if all are digits:
digits = '0123456789'
def isdigit(inputstring):
if not inputstring: return False
for char in inputstring:
if char not in digits:
return False
return True
Or make use of string comparisons:
def isdigit(inputstring):
if not inputstring: return False
for char in inputstring:
if not '0' <= char <= '9':
return False
return True
Your function is, unfortunately, way off. You don't define digit, nor do you loop over the characters of str. int is a type; strings (even individual characters) are not integers; and a string like -42 can be converted to an integer but '-42'.isdigit() returns False because '-' is not a digit.

#Martijn Pieters suggested how to fix your version; here for completeness is a more "pythonic" (and efficient) approach to the problem.
def my_isdigit(str):
return all('0'<=c<='9' for c in str)

You can use regular expressions
def my_isdigit(str):
return re.search("[^\d]", str) is None
Since there's some questions here are some simple tests:
print my_isdigit("02211")
> True
print my_isdigit("022x01")
> False
print my_isdigit("a02201")
> False

Related

Find if the contents of a string is in a word chosen randomly from list? [closed]

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

How to use recursion to determine if characters are in a string? [closed]

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
Right now I'm trying to use recursion of a function with two parameters to find whether or not the second is included in the first. As an example:
def recurseString(full, inclusive):
...............
With this I would take something along the lines of:
recurseString('jack','kcj')
and this would return "True" whereas something like:
recurseString('stan','xun')
would return "False"
I'm rather new to python so this is rather confusing. Any ideas on how to go about this problem?
I am guessing that you are looking for ...
In [51]: def recurseString(a,b):
....: if b == '': return True
....: else:
....: if len(b) == 1: return b in a
....: else: return (b[0] in a) and recurseString(a, b[1:])
....:
In [52]: recurseString('jack', 'kjc')
Out[52]: True
In [53]: recurseString('stan', 'xun')
Out[53]: False
However, there is no need for recursion. This is much better solved using all like so:
In [57]: all( [s in 'jack' for s in 'kjc'] )
Out[57]: True
which is far more Pythonic.
It is also possible to use reduce which is more functional but much less readable, since Python has much better ways of handling this.
In [60]: reduce(lambda x,y: (x and (y in 'jack')) , 'kjc', True)
Out[60]: True
Finally, this wouldn't be complete without using the set notation:
In [65]: (set('kjc') - set('jack')) == set()
Out[65]: True
So as you can see, the recursive version is the least suitable for this problem!
This will return True even if there are duplicate letters in inclusive but but only one in full:
def recurseString(full, inclusive):
if not inclusive:
return True
return inclusive[0] in full and recurseString(full, inclusive[1:])
>>> print recurseString('jack','kkkcccjjj')
True
The following requires full to contain the same number of duplicate letters - if inclusive has three k's full must have three k's:
def recurseString(full, inclusive, first_call = True):
# first time through, sort the arguments to make the algorithm easier
if first_call:
full, inclusive = map(sorted, (full, inclusive))
first_call = False
# two base cases, inclusive has been exhausted
if not inclusive:
return True
try:
index = full.index(inclusive[0])
except ValueError:
# and (2nd base case) first item of inclusive is not in full
return False
return recurseString(full[index+1:], inclusive[1:], first_call)
>>> print recurseString('jack','kkkcccjjj')
False
>>> print recurseString('jckackjkjc','kkkcccjjj')
True
>>>
Using the index method seemed like cheating -
def foo(full, inclusive, first_call = True):
if first_call:
full, inclusive = map(sorted, (full, inclusive))
if not full and inclusive:
return False
if not inclusive:
return True
if inclusive[0] == full[0]:
inclusive = inclusive[1:]
return foo(full[1:], inclusive, False)
assert not foo('','kkkcccjjj')
assert not foo('sun','xun')
assert not foo('jack','kkkcccjjj')
assert foo('s', 's')
assert foo('jckackjkjc','kkkcccjjj')
assert foo('','')
assert foo('a','')
To think about any problem recursively, you have to break it into a base case (or sometimes multiple base cases), and a recursive case (or sometimes multiple recursive cases).
I'm going to assume that "included by" means "each character in inclusive is also in full, and in fact each character that appears in inclusive N times is also in full at least N times".
So, if inclusive is empty, it's vacuously True.
But if the full is empty and inclusive is not, it's False.
Otherwise, if the first character of full is in inclusive, it's true iff full[1:] contains inclusive minus that character.
Otherwise, it's true iff full[1:] contains inclusive.
Now you just have to translate that to code.
If you don't need to handle repeated characters, you can simplify this by just testing inclusive[0] and recursing on inclusive[1:], instead of recursing on full[1:].
def recurseString(str1,str2):
if str2 == "": # str2 == "" all str2 letters are in str1
return True
elif str2[0] in str1:
return recurseString(str1, str2[1:]) # move to next letter in str2
return False # if we get here we have found a letter that is not in str1
In [22]: recurseString('stan','xun')
Out[22]: False
In [23]: recurseString('jack','kcj')
Out[23]: True
I don't know why you need recursive to implement it, it's difficult to read and understand.
MY GOD, It's a challenge for me to read my code.
def recurseSring(full, inclusive):
for i in range(len(full)):
for j in range(len(inclusive)):
if full[i] == inclusive[j]:
if recurseSring(full[i + 1:], inclusive[j + 1:]):
return True
if full[i] == inclusive[j] and len(inclusive) == 1:
return True
return False
if __name__ == "__main__":
if recurseSring('lifenglifeng001', 'lifeng'):
print('OK, equal')
else:
print('NOT equal')
Short but sweet.
def recurseString(full, incl):
return incl[:1] in full and (incl[:1] == '' or recurseString(full, incl[1:]))
The 'and' ensures both parts of the expression are true.
The first part - takes the first character of inclusive and searches for it in the full string:
incl[:1] in full #returns '' if incl is ''
The second part - this is true if you search with a null string (incl), have come to the end of incl OR if the recursive call is true called with the tail of incl used as the second arg:
incl[:1] == '' or recurseString(full, incl[1:])
#null check is first to prevent overflow
There's a simple approach for this without recursion: create two sets with the strings you want and check if one set is inside the other one.
def contains(text, chars):
textset = set(text)
charset = set(chars)
return charset.issubset(textset)
print contains("jackie", "ice") # True
print contains('jack','kcj') # True
print contains('stan','xun') # False

Distinguishing Between Words and Numbers in a String - Assertion Error [closed]

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
def checkio(words):
word = words.isalpha()
num = words.isdigit()
if word:
pass
if num:
pass
return True or False
print checkio(u"Hello World hello") == True, "Hello"
print checkio(u"He is 123 man") == False, "123 man"
print checkio(u"1 2 3 4") == False, "Digits"
print checkio(u"bla bla bla bla") == True, "Bla Bla"
print checkio(u"Hi") == False, "Hi"
It works fine. But -
When I replace print with assert, it gives Assertion Error. How do I OKAY that?
This is a puzzle that requires the use of .split() to solve it. I can't figure out how to use it, because when I convert it to list .isdigit and isalpha won't work. Need help.
Thanks!
Note - This is what the puzzle page says -
"Precondition: The input contains words and/or numbers. There are no mixed words (letters and digits combined).
0 < |words| < 100 (This is a simple task)." I ain't following this line.
To just address the one function you have so far:
def checkio(words):
word = words.isalpha() # word = either True or False
num = words.isdigit() # num = either True or False
if word: # these four
pass # lines don't
if num: # actually
pass # do anything
return True or False # always evaluates to return True
You never actually use the variables word and num you create at the start of the function (aside to determine whether to pass explicitly or implicitly), which should give you a good idea that your function probably isn't doing much!
A few snippets to help you:
words = words.split() # get list of individual words
len(words) # how many words
for word in words: # iterate through the words
You could keep a running count of how many alphabetic words you have seen in a row, and return True if it gets to three.
Using .split()
As you have already realized, .split() turns a string into a list of strings. By default, it will separate the string into its whitespace-delimited parts.
>>> "Hello World hello".split()
['Hello', 'World', 'hello']
Obviously, .isalpha() and .isdigit() are methods of strings, not lists. So you have to iterate through the strings inside your list, and check whether each is a word or number.
>>> for word in "Hello World hello".split():
if word.isalpha(): print "word!"
elif word.isdigit(): print "digit!"
word!
word!
word!
Now that you know how to go about checking each word, it is up to you to figure out how to determine if the string contains three words in succession.
Your AssertionErrors
Now, the reason why you had AssertionErrors was what you were returning with return True or False. Look:
>>> True or False
True
This means you are always returning True. Unfortunately this is simple boolean arithmetic so you need to read up on it. I think you were trying to say "this function will either return True, or return False," but that is not at all what you expressed. Anyway, if you replace this print statement with an assert:
print checkio(u"He is 123 man") == False
# goes to
assert checkio(u"He is 123 man") == False
You are saying assert True == False, hence the error. Try returning True if you can find three words in succession, and False otherwise.

Can't exclude some strings [duplicate]

This question already has answers here:
is_alpha coding that works like isalpha() in python
(4 answers)
Closed 9 years ago.
ASCII_LOWERCASE='abcdefghijklmnopqrstuvwxyz'
ASCII_UPPERCASE='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ASCII_ALL=ASCII_LOWERCASE+ASCII_UPPERCASE
def is_alpha(x):
for ch in x:
if ch not in ASCII_ALL:
return False
return True
This was my original code and it is still not returning False in cases like "". When the real isalpha() returns False in the case of '' or "". How to exclude all these cases?
Your loop
for ch in x:
Will never run if len(x) == 0, you go straight to
return True
Also, if you
import string
You can use string.ascii_uppercase and string.ascii_lowercase.
Empty strings will not trigger any code in the for loop, since for ch in '' is essentially a no-op here (there's nothing to iterate), so your is_alpha returns True for empty strings. You should add something like
if not x:
return False
to the beginning of your function.
(As a side note, your break statement is unnecessary since return False will exit the function.

How to find out if str has any number [closed]

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.

Categories

Resources