Skip to content

Instantly share code, notes, and snippets.

@tyler-austin
Created June 19, 2017 13:35
Show Gist options
  • Select an option

  • Save tyler-austin/33349c13bfa058c527826d860a1e247e to your computer and use it in GitHub Desktop.

Select an option

Save tyler-austin/33349c13bfa058c527826d860a1e247e to your computer and use it in GitHub Desktop.

Correct variable names consist only of Latin letters, digits and underscores and they can't start with a digit.

Check if the given string is a correct variable name.

Example

For name = "var_1__Int", the output should be
variableName(name) = true; For name = "qq-q", the output should be
variableName(name) = false; For name = "2w2", the output should be
variableName(name) = false.

Input/Output

  • [time limit] 4000ms (py3)

  • [input] string name

    Guaranteed constraints:

    1 ≤ name.length ≤ 10.
    
  • [output] boolean

    • true if name is a correct variable name, false otherwise.
import unittest
from variable_name import variable_name
class TestVariableName(unittest.TestCase):
def test_1(self):
name = 'var_1__Int'
result = variable_name(name)
self.assertTrue(result)
def test_2(self):
name = 'qq-q'
result = variable_name(name)
self.assertFalse(result)
def test_3(self):
name = '2w2'
result = variable_name(name)
self.assertFalse(result)
def test_4(self):
name = ' variable'
result = variable_name(name)
self.assertFalse(result)
def test_5(self):
name = 'va[riable0'
result = variable_name(name)
self.assertFalse(result)
def test_6(self):
name = 'variable0'
result = variable_name(name)
self.assertTrue(result)
def test_7(self):
name = 'a'
result = variable_name(name)
self.assertTrue(result)
if __name__ == '__main__':
unittest.main()
import re
def variable_name(name):
if name[0].isdigit():
return False
if not re.match('^[A-Za-z0-9_]*$', name):
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment