0

I want to determine if all the characters in a given string (say z) are alphanumeric (numbers and letters only).

The function should return True if the string is alphanumeric and False if not. I additionally want to avoid using conditional branching, relational, or Boolean operators, or any built in functions except type casting functions.

For any iteration, use a while loop with condition: True. Use try and except blocks.

what I have so far:

def is_alnum(z):
    i = 0
    y = 0
    while True:
        try:
            try:
                y = int(z[i])
            except(ValueError):
                   ### don't know what to insert
        except(IndexError):
            return True
        i += 1

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Katrina
  • 33
  • 4
  • `int(z[i])` will fail for letters. – Mark Ransom Aug 03 '20 at 19:34
  • 1
    Why did you edit your question by deleting everything?? Please learn how to use the site properly. If you have a different question just ask a new one, don't edit the existing one. – Asocia Aug 04 '20 at 05:11

2 Answers2

1

Here is a solution with just using the builtin function int:

def is_alnum(z):
    try:
        int(z, base=36)
    except ValueError:
        return False
    else:
        return True

>>> is_alnum('abc123')
True
>>> is_alnum('abc-123')
False

From the documentation:

base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35.

Asocia
  • 5,935
  • 2
  • 21
  • 46
0

How about this:

def is_alnum(z):
    i=1
    abcnum = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 
    'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
    'u', 'v', 'w', 'x', 'y', 'z'] + [str(i) for i in range(10)]    
    while True:
        try:
            chr = z[i-1].lower()
        except IndexError:
            return True
        try:
            idx = abcnum.index(chr)
        except ValueError as e:
            return False 
        i += 1

This will result in:

print(is_alnum("Yeah!!")) -> False (because of !!)

print(is_alnum("thisistrue")) -> True

JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
  • The question states that "conditional branching" isn't allowed, which I take to mean no `if`. – Mark Ransom Aug 03 '20 at 19:42
  • @MarkRansom You are correct, I hadn't read the question correctly. I have adapted the code to use try/except and not conditional branching. – JarroVGIT Aug 03 '20 at 19:54
  • @stovfl if you're going to do someone's homework for them, it's best to give an incomplete solution that they have to fix. – Mark Ransom Aug 04 '20 at 16:09