-
-
Save AshleyCoder3/ccca7c15a19eb387fa443c3f2c2242e7 to your computer and use it in GitHub Desktop.
Python brain teasers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Given a start integer and an ending integer (both inclusive), write a function that returns the count (not the sum) of all integers in the range (except integers that contain the digit 5). | |
| # Examples: | |
| # csAnythingButFive(1, 5) -> 1, 2, 3, 4, -> 4 (there are 4 integers in the range that do not contain the digit 5) | |
| # csAnythingButFive(1, 9) -> 1, 2, 3, 4, 6, 7, 8, 9 -> 8 | |
| # csAnythingButFive(4, 17) -> 4,6,7,8,9,10,11,12,13,14,16,17 -> 12 | |
| # Notes: | |
| # The output can contain the digit 5. | |
| # The start number will always be less than the end number (both numbers can also be negative). | |
| # [execution time limit] 4 seconds (py3) | |
| # [input] integer start | |
| # [input] integer end | |
| # [output] integer | |
| def csAnythingButFive(start, end): | |
| count = 0 | |
| new_list = [] | |
| for num in range(start, end + 1): | |
| str_num = str(num) | |
| if '5' in str_num : | |
| continue | |
| count += 1 | |
| return count | |
| print(csAnythingButFive(1, 5)) | |
| print(csAnythingButFive(1, 9)) | |
| print(csAnythingButFive(4, 17)) | |
| print(csAnythingButFive(-4, 17)) | |
| print(csAnythingButFive(0, 7)) | |
| print(csAnythingButFive(-14, -5)) | |
| #uper | |
| # input 2 integers | |
| # output 1 integer = a count of numbers in range(start, end) | |
| # start < end | |
| # the 2 nums cand be negative | |
| # PLAN | |
| # for loop in range(start, end + 1) | |
| # if num == 5 skip | |
| # else count(num) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Given a binary string (ASCII encoded), write a function that returns the equivalent decoded text. | |
| # Every eight bits in the binary string represents one character on the ASCII table. | |
| # Examples: | |
| # csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda" | |
| # 01101100 -> 108 -> "l" | |
| # 01100001 -> 97 -> "a" | |
| # 01101101 -> 109 -> "m" | |
| # 01100010 -> 98 -> "b" | |
| # 01100100 -> 100 -> "d" | |
| # 01100001 -> 97 -> "a" | |
| # csBinaryToASCII("") -> "" | |
| # Notes: | |
| # The input string will always be a valid binary string. | |
| # Characters can be in the range from "00000000" to "11111111" (inclusive). | |
| # In the case of an empty input string, your function should return an empty string. | |
| # [execution time limit] 4 seconds (py3) | |
| # [input] string binary | |
| # [output] string | |
| def csBinaryToASCII(binary): | |
| binary_letters = [] | |
| letters = '' | |
| if binary == "": | |
| return "" | |
| for index in range(0, len(binary), 8): | |
| binary_letters.append(binary[index:index + 8]) | |
| print(binary_letters) | |
| for string in binary_letters: | |
| binary_int = v=chr(int(string, 2)) | |
| print(binary_int) | |
| letters += binary_int | |
| return letters |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # You are given two strings, str_1 and str_2, where str_2 is generated by randomly shuffling str_1 and then adding one letter at a random position. | |
| # Write a function that returns the letter that was added to str_2. | |
| # Examples: | |
| # csFindAddedLetter(str_1 = "bcde", str_2 = "bcdef") -> "f" | |
| # csFindAddedLetter(str_1 = "", str_2 = "z") -> "z" | |
| # csFindAddedLetter(str_1 = "b", str_2 = "bb") -> "b" | |
| # csFindAddedLetter(str_1 = "bf", str_2 = "bfb") -> "b" | |
| # Notes: | |
| # str_1 and str_2 both consist of only lowercase alpha characters. | |
| # [execution time limit] 4 seconds (py3) | |
| # [input] string str_1 | |
| # [input] string str_2 | |
| # [output] string | |
| def csFindAddedLetter(str_1, str_2): | |
| m1 = {} | |
| for i in str_2: | |
| if i in m1: | |
| m1[i] += 1 | |
| else: | |
| m1[i] =1 | |
| for i in str_1: | |
| m1[i] -= 1 | |
| for h1 in m1: | |
| if m1[h1] == 1: | |
| return h1 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| You are given a non-empty array of integers. | |
| One element appears exactly once, with every other element appearing at least twice, perhaps more. | |
| # Write a function that can find and return the element that appears exactly once. | |
| # Example 1: | |
| # Input: [1,1,2,1] | |
| # Output: 2 | |
| # Example 2: | |
| # Input: [1,2,1,2,1,2,80] | |
| # Output: 80 | |
| # Note: You should be able to develop a solution that has O(n) time complexity. | |
| # [execution time limit] 4 seconds (py3) | |
| # [input] array.integer nums | |
| # [output] integer | |
| from collections import Counter | |
| def csFindTheSingleNumber(nums): | |
| frequency = Counter(nums) | |
| for i in frequency: | |
| if frequency[i] == 1: | |
| return i |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Create a function that concatenates the number 7 to the end of every chord in a list. If a chord already ends with a 7, ignore that chord. | |
| def csMakeItJazzy(chords): | |
| for index in range(len(chords)): | |
| if chords[index].__contains__("7"): | |
| continue | |
| elif chords == []: | |
| return [] | |
| else: | |
| chords[index] = chords[index] + "7" | |
| return chords |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Given a string text, you need to use the characters of text to form as many instances of the word "lambda" as possible. | |
| # You can use each character in text at most once. | |
| # Write a function that returns the maximum number of instances of "lambda" that can be formed. | |
| # Input: text = "mbxcdatlas" | |
| # Output: 1 | |
| # Example 2: | |
| # Input: text = "lalaaxcmbdtsumbdav" | |
| # Output: 2 | |
| # Example 3: | |
| # Input: text = "sctlamb" | |
| # Output: 0 | |
| # Notes: | |
| # text consists of lowercase English characters only | |
| # [execution time limit] 4 seconds (py3) | |
| # [input] string text | |
| # [output] integer | |
| def csMaxNumberOfLambdas(text): | |
| sub_string = "lambda" | |
| lambda_count = {'l': 0, 'a': 0, 'm': 0, 'b': 0, 'd': 0, 'a': 0} | |
| counts = [] | |
| for letter in text: | |
| if letter in lambda_count: | |
| lambda_count[letter] += 1 | |
| for key, value in lambda_count.items(): | |
| counts.append(value) | |
| return min(counts) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Challenge #6: | |
| Return the number (count) of vowels in the given string. | |
| We will consider `a, e, i, o, u as vowels for this challenge (but not y). | |
| The input string will only consist of lower case letters and/or spaces. | |
| """ | |
| def get_count(input_str): | |
| # Your code here | |
| vowel_counts = {} #this is a dictionary to store the vowels | |
| for vowel in "aeiou": | |
| count = input_str.count(vowel) | |
| vowel_counts[vowel] = count | |
| print(vowel_counts) | |
| counts = vowel_counts.values() | |
| return sum(counts) | |
| print(get_count("adela are mere")) | |
| """ | |
| Challenge #5: | |
| Create a function that returns the data type of a given argument. There are | |
| seven data types this challenge will be testing for: | |
| - List | |
| - Dictionary | |
| - String | |
| - Integer | |
| - Float | |
| - Boolean | |
| - Date | |
| Examples: | |
| - data_type([1, 2, 3, 4]) ➞ "list" | |
| - data_type({'key': "value"}) ➞ "dictionary" | |
| - data_type("This is an example string.") ➞ "string" | |
| - data_type(datetime.date(2018,1,1)) ➞ "date" | |
| Notes: | |
| - Return the name of the data type as a lowercase string. | |
| """ | |
| import datetime | |
| def data_type(value): | |
| # Your code here | |
| date = datetime.date | |
| if type(value) is int: | |
| return "integer" | |
| elif type(value) is str: | |
| return "string" | |
| elif type(value) is list: | |
| return "list" | |
| elif type(value) is dict: | |
| return "dictionary" | |
| elif type(value) is float: | |
| return "float" | |
| elif type(value) is bool: | |
| return "boolean" | |
| elif type(value) == date: | |
| return "date" | |
| print(data_type([1, 2, 3, 4])) | |
| print(data_type({'key': "value"})) | |
| print(data_type("This is an example string.")) | |
| print(data_type(datetime.date(2018,1,1))) | |
| """ | |
| Challenge #4: | |
| Create a function that changes specific words into emoticons. Given a sentence | |
| as a string, replace the words `smile`, `grin`, `sad`, and `mad` with their | |
| corresponding emoticons. | |
| word -> emoticon | |
| --- | |
| smile -> :D | |
| grin -> :) | |
| sad -> :( | |
| mad -> :P | |
| Examples: | |
| - emotify("Make me smile") ➞ "Make me :D" | |
| - emotify("Make me grin") ➞ "Make me :)" | |
| - emotify("Make me sad") ➞ "Make me :(" | |
| Notes: | |
| - The sentence always starts with "Make me". | |
| - Try to solve this without using conditional statements like if/else. | |
| """ | |
| def emotify(txt): | |
| # Your code here | |
| #````another option``` | |
| # new = txt.split(' ') | |
| # print(new) | |
| #```````````` | |
| new_list = list(txt) | |
| #print(new_list) | |
| sliced_list = new_list[8:] | |
| emotion = "".join(sliced_list) | |
| print(emotion) | |
| if emotion == "smile": | |
| return "Make me :D" | |
| elif emotion == "grin": | |
| return "Make me :)" | |
| else: | |
| return "Make me :(" | |
| print(emotify("Make me smile")) | |
| print(emotify("Make me grin")) | |
| print(emotify("Make me sad")) | |
| import math | |
| """ | |
| Challenge #3: | |
| Given a string of numbers separated by a comma and space, return the product of the numbers. | |
| Examples: | |
| - multiply_nums("2, 3") ➞ 6 | |
| - multiply_nums("1, 2, 3, 4") ➞ 24 | |
| - multiply_nums("54, 75, 453, 0") ➞ 0 | |
| - multiply_nums("10, -2") ➞ -20 | |
| Notes: | |
| - Bonus: Try to complete this challenge in one line! | |
| """ | |
| def multiply_nums(nums): | |
| # Your code here | |
| #nums = "2, 4, 6" | |
| integer_list = [] | |
| new_list = list(nums) | |
| sliced_list = new_list[0::3] | |
| print(sliced_list) | |
| for elem in sliced_list: | |
| int_elem = int(elem) | |
| integer_list.append(int_elem) | |
| print(type(int_elem)) | |
| return math.prod(integer_list) | |
| print(multiply_nums("2, 3")) | |
| """ | |
| Challenge #2: | |
| Given a list of numbers, create a function that returns the list but with each | |
| element's index in the list added to itself. You should add 0 to the number at | |
| index 0, add 1 to the number at index 1, etc. | |
| Examples: | |
| - add_indexes([0, 0, 0, 0, 0]) ➞ [0, 1, 2, 3, 4] | |
| - add_indexes([1, 2, 3, 4, 5]) ➞ [1, 3, 5, 7, 9] | |
| - add_indexes([5, 4, 3, 2, 1]) ➞ [5, 5, 5, 5, 5] | |
| Notes: | |
| - The input list will only contain integers. | |
| """ | |
| def add_indexes(numbers): | |
| # Your code here | |
| new_list = [] | |
| for index, value in enumerate(numbers): | |
| sum = index + value | |
| new_list.append(sum) | |
| return new_list | |
| enumerate(my_list) # tuples of the index and the value of the list | |
| list(enumerate(a_list)) #and makes it into an array | |
| for item in enumerate(a_list): | |
| print(item) | |
| for index, value in enumerate(a_list): | |
| print(index) or print(value) | |
| """ | |
| Challenge #1: | |
| Write a function that retrieves the last n elements from a list. | |
| Examples: | |
| - last([1, 2, 3, 4, 5], 1) ➞ [5] | |
| - last([4, 3, 9, 9, 7, 6], 3) ➞ [9, 7, 6] | |
| - last([1, 2, 3, 4, 5], 7) ➞ "invalid" | |
| - last([1, 2, 3, 4, 5], 0) ➞ [] | |
| Notes: | |
| - Return "invalid" if n exceeds the length of the list. | |
| - Return an empty list if n == 0. | |
| """ | |
| #list[-1] = last element | |
| #list[-2] = last 2 elements of the list | |
| def last(a, n): | |
| # Your code here | |
| if n > len(a): | |
| return "invalid" | |
| elif n == 0 : | |
| return [] | |
| else: | |
| return a[-n:] #the last 3/n elements | |
| print(last([1, 2, 3, 4, 5], 1)) | |
| """ | |
| Challenge #9: | |
| Given a string, write a function that returns the "middle" character of the | |
| word. | |
| If the word has an odd length, return the single middle character. If the word | |
| has an even length, return the middle two characters. | |
| Examples: | |
| - get_middle("test") -> "es" | |
| - get_middle("testing") -> "t" | |
| - get_middle("middle") -> "dd" | |
| - get_middle("A") -> "A" | |
| """ | |
| def get_middle(input_str): | |
| # Your code here | |
| return input_str[(len(input_str) -1) // 2: (len(input_str) + 2) // 2] | |
| print(get_middle("test")) | |
| print(get_middle("testing")) | |
| print(get_middle("middle")) | |
| print(get_middle("A")) | |
| print(get_middle("beyoudre")) | |
| print(get_middle("you")) | |
| #Given a string of words, return the length of the shortest word(s). | |
| #The input string will never be empty and you do not need to validate for different data types. | |
| def csShortestWord(input_str): | |
| word = map(len, input_str.split()) | |
| return min(word) | |
| # Given an array of integers, return the sum of all the positive integers in the array. | |
| # Examples: | |
| # csSumOfPositive([1, 2, 3, -4, 5]) -> 1 + 2 + 3 + 5 = 11 | |
| # csSumOfPositive([-3, -2, -1, 0, 1]) -> 1 | |
| # csSumOfPositive([-3, -2]) -> 0 | |
| # Notes: | |
| # If the input_arr does not contain any positive integers, the default sum should be 0. | |
| import math | |
| def csSumOfPositive(input_arr): | |
| new_array = [] | |
| for num in input_arr: | |
| if num > 0: | |
| new_array.append(num) | |
| else: | |
| continue | |
| return math.fsum(new_array) | |
| """ | |
| Challenge #10: | |
| Given a string of space separated integers, write a function that returns the | |
| maximum and minimum integers. | |
| Example: | |
| - max_and_min("1 2 3 4 5") -> "5 1" | |
| - max_and_min("1 2 -3 4 5") -> "5 -3" | |
| - max_and_min("1 9 3 4 -5") -> "9 -5" | |
| Notes: | |
| - All inputs are valid integers. | |
| - There will always be at least one number in the input string. | |
| - The return string must be two numbers separated by a single space, and | |
| the maximum number is first. | |
| """ | |
| import functools | |
| import operator | |
| def max_and_min(input_str): | |
| # Your code here | |
| new_list = list(map(int, input_str.split())) | |
| new_string = str(max(new_list)) + " " + str(min(new_list)) | |
| print(type(new_string)) | |
| return new_string | |
| print(max_and_min("1 2 3 4 5")) | |
| print(max_and_min("1 2 -3 4 5")) | |
| print(max_and_min("1 9 3 4 -5")) | |
| """ | |
| Challenge #10: | |
| Create a function that applies a discount d to every number in the list. | |
| Examples: | |
| - get_discounts([2, 4, 6, 11], "50%") ➞ [1, 2, 3, 5.5] | |
| - get_discounts([10, 20, 40, 80], "75%") ➞ [7.5, 15, 30, 60] | |
| - get_discounts([100], "45%") ➞ [45] | |
| Notes: | |
| - The discount is the percentage of the original price (i.e the discount of | |
| "75%" to 12 would be 9 as opposed to taking off 75% (making 3)). | |
| - There won't be any awkward decimal numbers, only 0.5 to deal with. | |
| """ | |
| import math | |
| def get_discounts(nums, percentage): | |
| # Your code here | |
| new_percentage = list(percentage) | |
| discount_str = int(new_percentage[0] + new_percentage[1]) | |
| discount = int(discount_str) / 100 | |
| print(discount) | |
| d = [] | |
| for num in nums: | |
| num = discount * num | |
| s = str(num) | |
| new_num = int(s.rstrip(".0")) if ".0" in s else float(s) | |
| d.append(new_num) | |
| return d | |
| print(get_discounts([2, 4, 6, 11], "50%")) | |
| print(get_discounts([10, 20, 40, 80], "75%")) | |
| print(get_discounts([100], "45%")) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| text = "Adela, hi!" | |
| # def csOppositeReverse(txt): | |
| # for i in range(len(txt)): | |
| # if re.match("^[a-z]+$", txt[i]): | |
| # txt[i] = txt[i].upper() | |
| # return txt[::-1] | |
| # elif re.match("^[A-Z]+$", txt[i]): | |
| # txt[i] = txt[i].lower() | |
| # return txt[::-1] | |
| def csOppositeReverse(txt): | |
| return txt.swapcase()[::-1] | |
| print(csOppositeReverse(text)) | |
| #puterea a doua a fiecarui digit intr un numar | |
| def csSquareAllDigits(n): | |
| return int(''.join(str(int(i)**2) for i in str(n))) | |
| #take out the vowels of a string | |
| import re | |
| def csRemoveTheVowels(txt): | |
| # vowels = ["a", "e", "i", "o", "u"] | |
| # return "".join([l for l in txt if l not in vowels]) | |
| return re.sub(r'[AEIOU]', "", txt, flags=re.IGNORECASE) | |
| print(csRemoveTheVowels(text)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Given a number, write a function that converts that number into a string that contains "raindrop sounds" corresponding to certain potential factors. A factor is a number that evenly divides into another number, leaving no remainder. The simplest way to test if one number is a factor of another is to use the modulo operator. | |
| # Here are the rules for csRaindrop. If the input number: | |
| # has 3 as a factor, add "Pling" to the result. | |
| # has 5 as a factor, add "Plang" to the result. | |
| # has 7 as a factor, add "Plong" to the result. | |
| # does not have any of 3, 5, or 7 as a factor, the result should be the digits of the input number. | |
| # Examples: | |
| # csRaindrops(28) -> "Plong" | |
| # 28 has 7 as a factor, but not 3 or 5. | |
| # csRaindrops(30) -> "PlingPlang" | |
| # 30 has both 3 and 5 as factors, but not 7. | |
| # csRaindrops(34) -> "34" | |
| # 34 is not factored by 3, 5, or 7. | |
| # [execution time limit] 4 seconds (py3) | |
| # [input] integer number | |
| # [output] string | |
| def csRaindrops(number): | |
| output_string = "" | |
| has_3_factor = output_string + "Pling" | |
| if number % 3 == 0: | |
| output_string += "Pling" | |
| elif number % 5 == 0: | |
| output_string += "Plang" | |
| elif number % 7 == 0: | |
| output_string += "Plong" | |
| elif output_string is "": | |
| output_string += str(number) | |
| return output_string |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Challenge #7: | |
| Given a string of lowercase and uppercase alpha characters, write a function | |
| that returns a string where each character repeats in an increasing pattern, | |
| starting at 1. Each character repetition starts with a capital letter and the | |
| rest of the repeated characters are lowercase. Each repetition segment is | |
| separated by a `-` character. | |
| Examples: | |
| - repeat_it("abcd") -> "A-Bb-Ccc-Dddd" | |
| - repeat_it("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" | |
| - repeat_it("cwAt") -> "C-Ww-Aaa-Tttt" | |
| """ | |
| def repeat_it(input_str): | |
| # Your code here | |
| new_list = list(input_str) | |
| empty = [] | |
| for index, letter in enumerate(new_list): | |
| letter = "-" + letter.upper() + (index * letter).lower() | |
| empty.append(letter) | |
| new_str = "".join(empty) | |
| transformed = list(new_str) | |
| good_string = transformed[1:] | |
| return ''.join(good_string) | |
| print(repeat_it("cwAt")) | |
| print(repeat_it("RqaEzty")) | |
| print(repeat_it("abcd")) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Given an integer, write a function that reverses the bits (in binary) and returns the integer result. | |
| # Examples: | |
| # csReverseIntegerBits(417) -> 267 | |
| # 417 in binary is 110100001. Reversing the binary is 100001011, which is 267 in decimal. | |
| # csReverseIntegerBits(267) -> 417 | |
| # csReverseIntegerBits(0) -> 0 | |
| # Notes: | |
| # The input integer will not be negative. | |
| # [execution time limit] 4 seconds (py3) | |
| # [input] integer n | |
| # [output] integer | |
| def csReverseIntegerBits(n): | |
| reversed_num = 0 | |
| while(n > 0): | |
| reversed_num = reversed_num << 1 | |
| if ( n & 1 == 1): | |
| reversed_num = reversed_num ^ 1 | |
| n = n >> 1 | |
| return reversed_num |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Write a function that returns the groups in the school by year (as a string), separated with a comma and space in the form of "1a, 1b, 1c, 1d, 2a, 2b (....) 6d, 7a, 7b, 7c, 7d". | |
| # Examples: | |
| # csSchoolYearsAndGroups(years = 7, groups = 4) ➞ "1a, 1b, 1c, 1d, 2a, 2b, 2c, 2d, 3a, 3b, 3c, 3d, 4a, 4b, 4c, 4d, 5a, 5b, 5c, 5d, 6a, 6b, 6c, 6d, 7a, 7b, 7c, 7d" | |
| # Notes: | |
| # 1 <= years <= 10 | |
| # 1 <= groups <=26 | |
| # [execution time limit] 4 seconds (py3) | |
| # [input] integer years | |
| # [input] integer groups | |
| # [output] string | |
| def schoolGroups(years, groups): | |
| alphabet = list(map(chr, range(97, 123))) | |
| emp_list = [] | |
| for year in range(1, years + 1): | |
| for group in range(0, groups): | |
| emp_list.append(f'{year}{alphabet[group]}') | |
| #print(emp_list) | |
| return ', '.join(emp_list) | |
| print(schoolGroups(1, 4)) | |
| print(schoolGroups(6, 7)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # You are given a parentheses sequence, check if it's regular. | |
| # Example | |
| # For s = "()()(())", the output should be | |
| # validParenthesesSequence(s) = true; | |
| # For s = "()()())", the output should be | |
| # validParenthesesSequence(s) = false. | |
| # Input/Output | |
| # [execution time limit] 4 seconds (py3) | |
| # [input] string s | |
| # A string, consisting only of '(' and ')'. | |
| # Guaranteed constraints: | |
| # 0 ≤ s.length ≤ 105. | |
| # [output] boolean | |
| # true is the sequence is regular and false otherwise. | |
| def validParenthesesSequence(s): | |
| stack = [] | |
| # Traversing the Expression | |
| for char in s: | |
| if char in ["(", "{", "["]: | |
| stack.append(char) | |
| else: | |
| if not stack: | |
| return False | |
| current_char = stack.pop() | |
| if current_char == '(': | |
| if char != ")": | |
| return False | |
| if current_char == '{': | |
| if char != "}": | |
| return False | |
| if current_char == '[': | |
| if char != "]": | |
| return False | |
| if stack: | |
| return False | |
| return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment