├── .gitignore ├── 46 Simple Python Exercises.pdf ├── README.md ├── problem_01.py ├── problem_02.py ├── problem_03.py ├── problem_04.py ├── problem_05.py ├── problem_06.py ├── problem_07.py ├── problem_07_alternative.py ├── problem_07_alternative_short.py ├── problem_08.py ├── problem_08_alternative.py ├── problem_09.py ├── problem_09_alternative.py ├── problem_10.py ├── problem_10_alternative.py ├── problem_11.py ├── problem_11_alternative.py ├── problem_12.py ├── problem_12_alternative.py ├── problem_13.py ├── problem_13_alternative.py ├── problem_14.py ├── problem_14_alternative.py ├── problem_15.py ├── problem_15_alternative.py ├── problem_16.py ├── problem_16_alternative.py ├── problem_17.py ├── problem_17_alternative.py ├── problem_18.py ├── problem_18_alternative.py ├── problem_19.py ├── problem_20.py ├── problem_20_alternative.py ├── problem_21.py ├── problem_21_alternative.py ├── problem_21_alternative_2.py ├── problem_22.py ├── problem_22_alternative.py ├── problem_23.py ├── problem_24.py ├── problem_25.py ├── problem_26.py ├── problem_27.py ├── problem_27_alternative.py ├── problem_28.py ├── problem_28_alternative.py ├── problem_29.py ├── problem_30.py ├── problem_30_alternative.py ├── problem_31.py ├── problem_31_alternative.py ├── problem_32.py ├── problem_32_alternative.py ├── problem_33.py ├── problem_34.py ├── problem_35.py ├── problem_36.py ├── problem_37.py ├── test.txt ├── test_numbered.txt └── words.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | .DS_Store 3 | *.pyc 4 | /static 5 | 6 | .idea 7 | *.idea 8 | 9 | venv/ 10 | venv/* 11 | 12 | .coverage 13 | cover 14 | xunittest.xml 15 | 16 | __pycache__ -------------------------------------------------------------------------------- /46 Simple Python Exercises.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arsho/46-Simple-Python-Exercises-Solutions/fd1c83e2247322a32aeb89f959043fb42f47a199/46 Simple Python Exercises.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 46-Simple-Python-Exercises-Solutions 2 | Solutions of '46 Simple Python Exercises' from http://www.ling.gu.se/~lager/python_exercises.html 3 | It includes a list of exercises to introduce people to Python programming language. 4 | 5 | This list of exercises comprises logical operators, loops, input and output, regular expressions and 6 | more in order for people to have a basic overview of the language. 7 | 8 | In order for better categorization, the exercises have been divided into 4 sections. 9 | 10 | 1. Very Simple Exercises 11 | 2. Higher Order Functions and List Comprehension 12 | 3. Simple exercises including Input and Output 13 | 4. Somewhat harder exercises 14 | 15 | This repository also includes the PDF file of the exercises. 16 | 17 | ## Contributing 18 | Everyone is welcome to contribute. Feel free to submit a pull request, issue or suggestion you may find relevant. 19 | 20 | 21 | ## Reference 22 | The original collection of exercises was created by Torbjörn Lager (torbjorn.lager@ling.gu.se) 23 | and can be found [here](http://www.ling.gu.se/~lager/python_exercises.html). -------------------------------------------------------------------------------- /problem_01.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if­ 5 | then­else construct available in Python. (It is true that Python has the max() function built in, but writing it 6 | yourself is nevertheless a good exercise.) 7 | ''' 8 | 9 | def max(num1,num2): 10 | if ((not isinstance(num1,int)) and (not isinstance(num1,float))) or ((not isinstance(num2,int)) and (not isinstance(num2,float))): 11 | raise TypeError("Both parameters should be integer or float.") 12 | if num1>num2: 13 | return num1 14 | else: 15 | return num2 16 | print(max(3,69)) 17 | -------------------------------------------------------------------------------- /problem_02.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | Define a function max_of_three() that takes three numbers as arguments and returns the largest of 5 | them. 6 | ''' 7 | 8 | def max_of_three(num1, num2, num3): 9 | if ((not isinstance(num1,int)) and (not isinstance(num1,float))) or ((not isinstance(num2,int)) and (not isinstance(num2,float))) or ((not isinstance(num3,int)) and (not isinstance(num3,float))): 10 | raise TypeError("All three parameters should be integer or float.") 11 | max_num = num1 12 | if(num2>max_num): 13 | max_num = num2 14 | if(num3>max_num): 15 | max_num = num3 16 | return max_num 17 | #return max(num1,max(num2,num3)) 18 | 19 | print(max_of_three(36,-366,900)) 20 | -------------------------------------------------------------------------------- /problem_03.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | Define a function that computes the length of a given list or string. (It is true that Python has the len() 5 | function built in, but writing it yourself is nevertheless a good exercise.) 6 | ''' 7 | 8 | def custom_len(given_list_or_string): 9 | if(not isinstance(given_list_or_string, str)) and (not isinstance(given_list_or_string, list)): 10 | raise TypeError("Parameter should be list or string type") 11 | cnt = 0 12 | for elem in given_list_or_string: 13 | cnt+=1 14 | return cnt 15 | print(custom_len("asd")) 16 | -------------------------------------------------------------------------------- /problem_04.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False 5 | otherwise. 6 | ''' 7 | 8 | def check_vowel(single_char): 9 | if(not isinstance(single_char, str)) or (len(single_char)!=1): 10 | raise TypeError("Parameter should be a single character.") 11 | single_char = single_char.lower() 12 | return single_char in ['a','e','i','o','u'] 13 | print(check_vowel("U")) 14 | -------------------------------------------------------------------------------- /problem_05.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's 5 | language"). That is, double every consonant and place an occurrence of "o" in between. For example, 6 | translate("this is fun") should return the string "tothohisos isos fofunon". 7 | ''' 8 | import string 9 | def translate(text): 10 | if(not isinstance(text, str)): 11 | raise TypeError("Parameter should be string.") 12 | 13 | all_letter = string.ascii_letters 14 | vowel_letter = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'] 15 | constant_letter = [c for c in all_letter if c not in vowel_letter] 16 | 17 | output = "" 18 | for c in text: 19 | if c in constant_letter: 20 | output+=c+"o"+c 21 | else: 22 | output+=c 23 | return output 24 | print(translate("this is fun")) 25 | -------------------------------------------------------------------------------- /problem_06.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | Define a function sum() and a function multiply() that sums and multiplies (respectively) all the 5 | numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 6 | 2, 3, 4]) should return 24. 7 | ''' 8 | def sum(num_list): 9 | total = 0 10 | for c in num_list: 11 | total+=c 12 | return total 13 | 14 | def multiply(num_list): 15 | total = 1 16 | for c in num_list: 17 | total*=c 18 | return total 19 | 20 | print(sum([1,2,3,4])) 21 | print(multiply([1,2,3,4])) 22 | -------------------------------------------------------------------------------- /problem_07.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function reverse()that computes the reversal 3 | of a string. For example, reverse("I am testing") 4 | should return the string "gnitset ma I". 5 | ''' 6 | 7 | def reverse(string): 8 | length = len(string) 9 | ab = '' 10 | for i in range(length): 11 | ab += string[length-1] 12 | length -= 1 13 | return ab 14 | 15 | print(reverse("I am testing")) 16 | -------------------------------------------------------------------------------- /problem_07_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function reverse()that computes the reversal 3 | of a string. For example, reverse("I am testing") 4 | should return the string "gnitset ma I". 5 | ''' 6 | 7 | def reverse(passed_string): 8 | passed_string_length = len(passed_string) 9 | reverse_string = '' 10 | for i in range(passed_string_length-1,-1,-1): 11 | reverse_string += passed_string[i] 12 | return reverse_string 13 | 14 | print(reverse("I am testing")) 15 | -------------------------------------------------------------------------------- /problem_07_alternative_short.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function reverse()that computes the reversal 3 | of a string. For example, reverse("I am testing") 4 | should return the string "gnitset ma I". 5 | ''' 6 | 7 | def reverse(passed_string): 8 | return passed_string[::-1] 9 | 10 | print(reverse("I am testing")) 11 | -------------------------------------------------------------------------------- /problem_08.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function is_palindrome()that recognizes 3 | palindromes (i.e. words that look the same written 4 | backwards). For example, is_palindrome("radar") 5 | should return True 6 | ''' 7 | 8 | def is_palindrome(string): 9 | ab = '' 10 | length = len(string) 11 | for i in range(length): 12 | ab += string[length-1] 13 | length -= 1 14 | if string == ab: 15 | return True 16 | else: 17 | return False 18 | 19 | 20 | print(is_palindrome("radar")) 21 | print(is_palindrome("abcde")) 22 | -------------------------------------------------------------------------------- /problem_08_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function is_palindrome()that recognizes 3 | palindromes (i.e. words that look the same written 4 | backwards). For example, is_palindrome("radar") 5 | should return True 6 | ''' 7 | 8 | def is_palindrome(passed_string): 9 | return passed_string==passed_string[::-1] 10 | 11 | print(is_palindrome("radar")) 12 | print(is_palindrome("abcde")) 13 | -------------------------------------------------------------------------------- /problem_09.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function is_member()that takes a value 3 | (i.e. a number, string, etc) x and a list of 4 | values a, and returns True if x is a member of a, 5 | False otherwise.(Note that this is exactly what 6 | the in operator does, but for the sake of the 7 | exercise you should pretend Python did not 8 | have this operator.) 9 | ''' 10 | 11 | def is_member(item,list_var): 12 | length = len(list_var) 13 | i=0 14 | while i < length: 15 | if item == list_var[i-1]: 16 | return True 17 | i += 1 18 | return False 19 | 20 | abc = [1,4,6,9,34] 21 | print(is_member(9,abc)) 22 | print(is_member(11,abc)) 23 | 24 | 25 | -------------------------------------------------------------------------------- /problem_09_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function is_member()that takes a value 3 | (i.e. a number, string, etc) x and a list of 4 | values a, and returns True if x is a member of a, 5 | False otherwise.(Note that this is exactly what 6 | the in operator does, but for the sake of the 7 | exercise you should pretend Python did not 8 | have this operator.) 9 | ''' 10 | 11 | def is_member(item,list_var): 12 | list_length = len(list_var) 13 | for i in range(list_length): 14 | if item==list_var[i]: 15 | return True 16 | return False 17 | 18 | abc = [1,4,6,9,34] 19 | print(is_member(9,abc)) 20 | print(is_member(11,abc)) 21 | 22 | 23 | -------------------------------------------------------------------------------- /problem_10.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function overlapping()that takes two lists 3 | and returns True if they have at least one member 4 | in common, False otherwise. You may use your 5 | is_member()function, or the in operator, but for the 6 | sake of the exercise, you should (also) write 7 | it using two nested for-loops 8 | ''' 9 | 10 | def overlapping(list1,list2): 11 | for i in list1: 12 | for j in list2: 13 | if i == j: 14 | return True 15 | 16 | return False 17 | 18 | a = [3,4,5,6,7] 19 | b = [6,7,8,9,10] 20 | c = [91,92,93] 21 | 22 | print(overlapping(a,b)) 23 | print(overlapping(a,c)) 24 | -------------------------------------------------------------------------------- /problem_10_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function overlapping()that takes two lists 3 | and returns True if they have at least one member 4 | in common, False otherwise. You may use your 5 | is_member()function, or the in operator, but for the 6 | sake of the exercise, you should (also) write 7 | it using two nested for-loops 8 | ''' 9 | 10 | def overlapping(list1,list2): 11 | return len([elem for elem in list1 if elem in list2])>0 12 | 13 | a = [3,4,5,6,7] 14 | b = [6,7,8,9,10] 15 | c = [91,92,93] 16 | 17 | print(overlapping(a,b)) 18 | print(overlapping(a,c)) 19 | -------------------------------------------------------------------------------- /problem_11.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function generate_n_chars()that takes 3 | an integer n and a character c and returns a string, 4 | n characters long, consisting only of c:s. For 5 | example, generate_n_chars(5,"x")should return 6 | the string "xxxxx". (Python is unusual 7 | in that you can actually write an expression 8 | 5 * "x"that will evaluate to 9 | "xxxxx". For the sake of the exercise you should 10 | ignore that the problem can 11 | be solved in this manner.) 12 | ''' 13 | 14 | def generate_n_chars(n,c): 15 | s = '' 16 | for i in range(n): 17 | s += c 18 | return s 19 | 20 | print(generate_n_chars(5,"x")) 21 | -------------------------------------------------------------------------------- /problem_11_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function generate_n_chars()that takes 3 | an integer n and a character c and returns a string, 4 | n characters long, consisting only of c:s. For 5 | example, generate_n_chars(5,"x")should return 6 | the string "xxxxx". (Python is unusual 7 | in that you can actually write an expression 8 | 5 * "x"that will evaluate to 9 | "xxxxx". For the sake of the exercise you should 10 | ignore that the problem can 11 | be solved in this manner.) 12 | ''' 13 | 14 | def generate_n_chars(n,c): 15 | s = ''.join([c for i in range(n)]) 16 | return s 17 | 18 | print(generate_n_chars(5,"x")) 19 | -------------------------------------------------------------------------------- /problem_12.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a procedure histogram() that takes a list of 3 | integers and prints a histogram to the screen. 4 | For example, histogram([4, 9, 7])should print the following: 5 | 6 | **** 7 | ********* 8 | ******* 9 | ''' 10 | 11 | def histogram(list_var): 12 | for i in list_var: 13 | print('*'*i) 14 | 15 | histogram([4, 9, 7]) 16 | 17 | -------------------------------------------------------------------------------- /problem_12_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a procedure histogram() that takes a list of 3 | integers and prints a histogram to the screen. 4 | For example, histogram([4, 9, 7])should print the following: 5 | 6 | **** 7 | ********* 8 | ******* 9 | ''' 10 | 11 | def histogram(list_var): 12 | s='\n'.join(['*'*i for i in list_var]) 13 | return s 14 | 15 | print(histogram([4, 9, 7])) 16 | 17 | -------------------------------------------------------------------------------- /problem_13.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The function max()from exercise 1) and the function 3 | max_of_three()from exercise 2) will only work for 4 | two and three numbers, respectively. But 5 | suppose we have a much larger number of numbers, 6 | or suppose we cannot tell in advance how many 7 | they are? Write a function max_in_list()that takes a 8 | list of numbers and returns the largest one 9 | ''' 10 | 11 | def a(listname): 12 | length = len(listname) 13 | tmp = [] 14 | for i in range(0,length-1): 15 | maximum = max(listname[i],listname[i+1]) 16 | tmp.append(maximum) 17 | return tmp 18 | 19 | def max_in_list(abc): 20 | if len(abc) == 1: 21 | return abc[0] 22 | else: 23 | return max_in_list(a(abc)) 24 | 25 | ab = [3,7,98,34,12,14] 26 | print(max_in_list(ab)) 27 | 28 | 29 | 30 | ###################################################### 31 | ###################### shortcut ###################### 32 | ###################################################### 33 | 34 | def maximum(list_var): 35 | list_var.sort() 36 | return list_var[-1] 37 | print(maximum(ab)) 38 | -------------------------------------------------------------------------------- /problem_13_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The function max()from exercise 1) and the function 3 | max_of_three()from exercise 2) will only work for 4 | two and three numbers, respectively. But 5 | suppose we have a much larger number of numbers, 6 | or suppose we cannot tell in advance how many 7 | they are? Write a function max_in_list()that takes a 8 | list of numbers and returns the largest one 9 | ''' 10 | 11 | def maximum(list_var): 12 | return max(list_var) 13 | print(maximum([32,43,2,3,45,6,43])) 14 | -------------------------------------------------------------------------------- /problem_14.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program that maps a list of words into a list 3 | of integers representing 4 | the lengths of the correponding words 5 | ''' 6 | 7 | def count(list_var): 8 | value = [] 9 | for i in list_var: 10 | count = 0 11 | for j in i: 12 | count += 1 13 | value.append(count) 14 | return value 15 | 16 | ab = ['abc','defgh','pqrstuvw'] 17 | print(count(ab)) 18 | -------------------------------------------------------------------------------- /problem_14_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program that maps a list of words into a list 3 | of integers representing 4 | the lengths of the correponding words 5 | ''' 6 | 7 | def map_word_length(word_list): 8 | word_length = [len(single_word) for single_word in word_list] 9 | word_map = dict(zip(word_list,word_length)) 10 | return word_map 11 | 12 | word_list = ['abc','defgh','pqrstuvw'] 13 | word_map = map_word_length(word_list) 14 | print(word_map) 15 | -------------------------------------------------------------------------------- /problem_15.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function find_longest_word()that takes a 3 | list of words and returns the 4 | length of the longest one 5 | ''' 6 | 7 | 8 | def countmax(list): 9 | value = [] 10 | for i in list: 11 | value.append(len(i)) 12 | value.sort() 13 | return value[-1] 14 | 15 | 16 | ab = ['abc','defgh','pqrstuvw',''] 17 | print(countmax(ab)) 18 | -------------------------------------------------------------------------------- /problem_15_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function find_longest_word()that takes a 3 | list of words and returns the 4 | length of the longest one 5 | ''' 6 | 7 | 8 | def find_longest_word(word_list): 9 | word_length = [len(word) for word in word_list] 10 | return max(word_length) 11 | 12 | 13 | word_list = ['abc','defgh','pqrstuvw',''] 14 | print(find_longest_word(word_list)) 15 | -------------------------------------------------------------------------------- /problem_16.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function filter_long_words()that takes 3 | a list of words and an integer 4 | n and returns the list of words that are longer than n 5 | ''' 6 | 7 | def filter_long_words(list_var,n): 8 | gt = [] 9 | for x in list_var: 10 | if len(x) > n: 11 | gt.append(x) 12 | return gt 13 | 14 | ab = ['abc','defgh','pqrstuvw','','abdghtfd'] 15 | print(filter_long_words(ab,5)) 16 | -------------------------------------------------------------------------------- /problem_16_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function filter_long_words()that takes 3 | a list of words and an integer 4 | n and returns the list of words that are longer than n 5 | ''' 6 | 7 | def filter_long_words(word_list,n): 8 | return [word for word in word_list if len(word)>n] 9 | 10 | word_list = ['abc','defgh','pqrstuvw','','abdghtfd'] 11 | print(filter_long_words(word_list,5)) 12 | -------------------------------------------------------------------------------- /problem_17.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a version of a palindrome recognizer that 3 | also accepts phrase palindromes such as "Go hang a 4 | salami I'm a lasagna hog.", "Was it a rat I 5 | saw?", "Step on no pets", "Sit on a potato pan, 6 | Otis", "Lisa Bonet ate no basil", 7 | "Satan, oscillate my metallic sonatas", "I roamed under 8 | it as a tired nude Maori", "Rise to vote sir", or the 9 | exclamation "Dammit, I'm mad!". Note that 10 | punctuation, capitalization, and spacing are usually ignored 11 | ''' 12 | 13 | def palindrome(string): 14 | string = string.lower() #only string.lower won't work 15 | string = string.replace(" ","") #must be contained in 16 | tem = ['.',',','!','?','\"',"\'"] #variable :) 17 | for i in tem: 18 | string = string.replace(i,"") 19 | tmp='' 20 | length = len(string) 21 | for i in range(length): 22 | tmp += string[length-1] 23 | length -= 1 24 | if string == tmp: 25 | return True 26 | else: 27 | return False 28 | 29 | ab = "Was it a rat I saw?" 30 | print (palindrome(ab)) 31 | -------------------------------------------------------------------------------- /problem_17_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a version of a palindrome recognizer that 3 | also accepts phrase palindromes such as "Go hang a 4 | salami I'm a lasagna hog.", "Was it a rat I 5 | saw?", "Step on no pets", "Sit on a potato pan, 6 | Otis", "Lisa Bonet ate no basil", 7 | "Satan, oscillate my metallic sonatas", "I roamed under 8 | it as a tired nude Maori", "Rise to vote sir", or the 9 | exclamation "Dammit, I'm mad!". Note that 10 | punctuation, capitalization, and spacing are usually ignored 11 | ''' 12 | 13 | def check_palindrome(passed_string): 14 | passed_string = passed_string.lower() 15 | passed_string = ''.join([c for c in passed_string if c.isalnum()]) 16 | return passed_string==passed_string[::-1] 17 | 18 | test_string1 = "Was it a rat I saw?" 19 | test_string2 = "Step on no pets" 20 | test_string3 = "Not palindrome at all!" 21 | 22 | print (check_palindrome(test_string1)) 23 | print (check_palindrome(test_string2)) 24 | print (check_palindrome(test_string3)) 25 | 26 | -------------------------------------------------------------------------------- /problem_18.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A pangram is a sentence that contains all the letters of 3 | the English alphabet at least once, for example: The 4 | quick brown fox jumps over the lazy dog. Your 5 | task here is to write a function to check a sentence to 6 | see if it is a pangram or not 7 | ''' 8 | 9 | def pangram(string): 10 | string = string.lower() 11 | alphabet = ['a','b','c','d','e','f','g','h',\ 12 | 'i','j','k','l','m','n','o','p',\ 13 | 'q','r','s','t','u','v','w','x','y','z'] 14 | 15 | a = 0 16 | for i in alphabet: 17 | if i not in string: 18 | print("it's not a pangram") 19 | a = 5 20 | break 21 | 22 | if a != 5: 23 | print("it's a pangram") 24 | 25 | ab = "The quick brown fox jumps over the lazy dog." 26 | pangram(ab) 27 | -------------------------------------------------------------------------------- /problem_18_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A pangram is a sentence that contains all the letters of 3 | the English alphabet at least once, for example: The 4 | quick brown fox jumps over the lazy dog. Your 5 | task here is to write a function to check a sentence to 6 | see if it is a pangram or not 7 | ''' 8 | 9 | def check_pangram(passed_string): 10 | passed_string = passed_string.lower() 11 | char_set = set(passed_string) 12 | letter_list = [c for c in char_set if c.isalpha()] 13 | return len(letter_list)==26 14 | 15 | test_string1 = "The quick brown fox jumps over the lazy dog." 16 | test_string2 = "This line has not all 26 characters. Okay?" 17 | print(check_pangram(test_string1)) 18 | print(check_pangram(test_string2)) 19 | -------------------------------------------------------------------------------- /problem_19.py: -------------------------------------------------------------------------------- 1 | ''' 2 | "99 Bottles of Beer" is a traditional song in the United States and Canada. It is popular to sing on long trips, 3 | as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's 4 | simple lyrics are as follows: 5 | 99 bottles of beer on the wall, 99 bottles of beer. 6 | Take one down, pass it around, 98 bottles of beer on the wall. 7 | The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or 8 | singers reach zero. 9 | Your task here is write a Python program capable of generating all the verses of the song 10 | ''' 11 | 12 | def sing_99_bottles_of_beer(): 13 | n = 99 14 | song = '' 15 | for i in range(n,0,-1): 16 | song+=str(i)+' bottles of beer on the wall, '+str(i)+' bottles of beer.\n\ 17 | Take one down, pass it around, '+str(i-1)+' bottles of beer on the wall.\n\n' 18 | return song 19 | 20 | print(sing_99_bottles_of_beer()) 21 | -------------------------------------------------------------------------------- /problem_20.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Represent a small bilingual lexicon as a Python dictionary 3 | in the following fashion {"merry":"god", "christmas":"jul", 4 | "and":"och", "happy":gott", "new":"nytt", "year":"år"} 5 | and use it to translate your Christmas cards from 6 | English into Swedish. That is, write a function 7 | translate()that takes a list of 8 | English words and returns a list of Swedish words 9 | ''' 10 | 11 | dic = {"merry":"god", "christmas":"jul",\ 12 | "and":"och", "happy":"gott", "new":"nytt", "year":"år"} 13 | 14 | def translate(list_eng): 15 | dic = {"merry":"god", "christmas":"jul",\ 16 | "and":"och", "happy":"gott", "new":"nytt", "year":"år"} 17 | list_dic = [] 18 | for i in list_eng: 19 | list_dic.append(dic[i]) 20 | return list_dic 21 | 22 | ab = ["merry","happy"] 23 | print(translate(ab)) 24 | -------------------------------------------------------------------------------- /problem_20_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Represent a small bilingual lexicon as a Python dictionary 3 | in the following fashion {"merry":"god", "christmas":"jul", 4 | "and":"och", "happy":gott", "new":"nytt", "year":"år"} 5 | and use it to translate your Christmas cards from 6 | English into Swedish. That is, write a function 7 | translate()that takes a list of 8 | English words and returns a list of Swedish words 9 | ''' 10 | 11 | word_map = {"merry":"god", "christmas":"jul",\ 12 | "and":"och", "happy":"gott", "new":"nytt", "year":"år"} 13 | 14 | def translate_to_swedish(english_word_list): 15 | return [word_map.get(k) if word_map.get(k)!=None else k for k in english_word_list] 16 | 17 | english_word_list = ["merry","christmas","dear"] 18 | print(translate_to_swedish(english_word_list)) 19 | -------------------------------------------------------------------------------- /problem_21.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function char_freq()that takes a string and 3 | builds a frequency listing of the characters contained 4 | in it. Represent the frequency listing as a Python 5 | dictionary. Try it with something like 6 | char_freq("abbabcbdbabdbdbabababcbcbab") 7 | ''' 8 | 9 | def char_freq(passed_string): 10 | char_freq_dic = dict() 11 | for c in passed_string: 12 | if c in char_freq_dic.keys(): 13 | char_freq_dic[c]=char_freq_dic.get(c)+1 14 | else: 15 | char_freq_dic[c]=1 16 | char_sorted_dic = sorted(char_freq_dic.items()) 17 | return char_sorted_dic 18 | 19 | print(char_freq("abbabcGDAbdbabdbdbababajsdhfdgfjsgfygbcbcbab")) 20 | 21 | -------------------------------------------------------------------------------- /problem_21_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function char_freq()that takes a string and 3 | builds a frequency listing of the characters contained 4 | in it. Represent the frequency listing as a Python 5 | dictionary. Try it with something like 6 | char_freq("abbabcbdbabdbdbabababcbcbab") 7 | ''' 8 | import collections 9 | def char_freq(passed_string): 10 | return sorted(dict(collections.Counter(passed_string)).items()) 11 | 12 | print(char_freq("abbabcGDAbdbabdbdbababajsdhfdgfjsgfygbcbcbab")) 13 | 14 | -------------------------------------------------------------------------------- /problem_21_alternative_2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function char_freq()that takes a string and builds a 3 | frequency listing of the characters contained in it. 4 | Represent the frequency listing as a Python dictionary. 5 | Try it with something like 6 | char_freq("abbabcbdbabdbdbabababcbcbab") 7 | ''' 8 | 9 | import collections 10 | def char_freq(string): 11 | return sorted(collections.Counter(list(string)).items()) 12 | 13 | print(char_freq("abbabcbdbabdbdbabababcbcbab")) 14 | -------------------------------------------------------------------------------- /problem_22.py: -------------------------------------------------------------------------------- 1 | """ 2 | In cryptography, a Caesar cipher is a very simple encryption 3 | techniques in which each letter in the plain text is 4 | replaced by a letter some fixed number of 5 | positions down the alphabet. For example, with a shift of 3, 6 | A would be replaced by D, B would become E, and so on. 7 | The method is named after Julius Caesar, who used it to 8 | communicate with his generals. ROT-13 ("rotate 9 | by 13 places") is a widely used example of a Caesar cipher 10 | where the shift is 13. In Python, the key for ROT-13 may 11 | be represented by means of the following dictionary: 12 | 13 | key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 14 | 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 15 | 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 16 | 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 17 | 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 18 | 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 19 | 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'} 20 | 21 | Your task in this exercise is to implement an encoder/ 22 | decoder of ROT-13. Once you're done, you will be able to 23 | read the following secret message: 24 | 25 | Pnrfne pvcure? V zhpu cersre Pnrfne fnynq! 26 | 27 | Note that since English has 26 characters, your ROT-13 program 28 | will be able to both encode and decode texts written in English. 29 | """ 30 | 31 | def ROT_13(string): 32 | 33 | key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 34 | 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 35 | 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 36 | 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 37 | 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 38 | 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 39 | 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'} 40 | 41 | code = '' 42 | for i in string: 43 | try: 44 | code += key[i] 45 | except: 46 | code += i # for space characters 47 | return code 48 | 49 | print(ROT_13('Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!')) 50 | 51 | 52 | -------------------------------------------------------------------------------- /problem_22_alternative.py: -------------------------------------------------------------------------------- 1 | """ 2 | In cryptography, a Caesar cipher is a very simple encryption 3 | techniques in which each letter in the plain text is 4 | replaced by a letter some fixed number of 5 | positions down the alphabet. For example, with a shift of 3, 6 | A would be replaced by D, B would become E, and so on. 7 | The method is named after Julius Caesar, who used it to 8 | communicate with his generals. ROT-13 ("rotate 9 | by 13 places") is a widely used example of a Caesar cipher 10 | where the shift is 13. In Python, the key for ROT-13 may 11 | be represented by means of the following dictionary: 12 | 13 | key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 14 | 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 15 | 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 16 | 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 17 | 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 18 | 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 19 | 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'} 20 | 21 | Your task in this exercise is to implement an encoder/ 22 | decoder of ROT-13. Once you're done, you will be able to 23 | read the following secret message: 24 | 25 | Pnrfne pvcure? V zhpu cersre Pnrfne fnynq! 26 | 27 | Note that since English has 26 characters, your ROT-13 program 28 | will be able to both encode and decode texts written in English. 29 | """ 30 | import string 31 | lowercase_normal = list(string.ascii_lowercase) 32 | lowercase_encode = [chr(((ord(c)+13-ord('a'))%26)+ord('a')) for c in lowercase_normal] 33 | uppercase_normal = list(string.ascii_uppercase) 34 | uppercase_encode = [chr(((ord(c)+13-ord('A'))%26)+ord('A')) for c in uppercase_normal] 35 | 36 | def ROT_13_encoder(passed_string): 37 | encoder_map=dict(zip(lowercase_normal,lowercase_encode)).copy() 38 | encoder_map.update(dict(zip(uppercase_normal,uppercase_encode))) 39 | output_string = '' 40 | for c in passed_string: 41 | output_string+=encoder_map.get(c,c) 42 | return output_string 43 | 44 | def ROT_13_decoder(passed_string): 45 | decoder_map=dict(zip(lowercase_encode,lowercase_normal)).copy() 46 | decoder_map.update(dict(zip(uppercase_encode,uppercase_normal))) 47 | output_string = '' 48 | for c in passed_string: 49 | output_string+=decoder_map.get(c,c) 50 | return output_string 51 | 52 | print(ROT_13_encoder(ROT_13_decoder('Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!'))) 53 | print(ROT_13_decoder('Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!')) 54 | 55 | 56 | -------------------------------------------------------------------------------- /problem_23.py: -------------------------------------------------------------------------------- 1 | """ 2 | Define a simple "spelling correction" function correct() that takes a string and 3 | sees to it that 4 | 1) two or more occurrences of the space character is compressed into one, 5 | and 6 | 2) inserts an extra space after a period if the period is directly followed 7 | by a letter. 8 | 9 | E.g. correct("This is very funny and cool.Indeed!") 10 | should return 11 | "This is very funny and cool. Indeed!" 12 | 13 | Tip: Use regular expressions! 14 | """ 15 | import re 16 | def correct(passed_line): 17 | passed_line = re.sub("\s{2,}"," ",passed_line) 18 | passed_line = re.sub(r'\.(\w)',r'. \1',passed_line) 19 | return passed_line 20 | 21 | print(correct("This is very funny and cool.Indeed!okay. bye.")) 22 | 23 | 24 | -------------------------------------------------------------------------------- /problem_24.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The third person singular verb form in English is distinguished 3 | by the suffix -s,which is added to the stem of the infinitive 4 | form: run -> runs. A simple set of rules can be given as follows: 5 | 6 | a. If the verb ends in y, remove it and add ies 7 | b. If the verb ends in o, ch, s, sh, x or z, add es 8 | c. By default just add s 9 | 10 | Your task in this exercise is to define a function make_3sg_form() 11 | which given a verb in infinitive form returns its third person 12 | singular form. Test your function with words like try, brush, 13 | run and fix. Note however that the rules must be 14 | regarded as heuristic, in the sense that you must not expect them 15 | to work for all cases. Tip: Check out the string method endswith() 16 | ''' 17 | 18 | def make_3sg_form(string): 19 | 20 | con_2 = ('o','ch','s','sh','x','z') # it's a tuple 21 | 22 | if string.endswith('y'): 23 | string = string[:-1] 24 | string += 'ies' 25 | 26 | elif string.endswith(con_2): # doesn't work on list 27 | string += 'es' # but tuple 28 | 29 | else: 30 | string += 's' 31 | 32 | return string 33 | 34 | 35 | 36 | verbs = ['try', 'brush' ,'run', 'fix'] 37 | for item in verbs: 38 | print(make_3sg_form(item)) 39 | -------------------------------------------------------------------------------- /problem_25.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In English, the present participle is formed by adding the 3 | suffix -ing to the infinite form: go -> going. A simple set 4 | of heuristic rules can be given as follows: 5 | 6 | a. If the verb ends in e, drop the e and add ing 7 | (if not exception: be, see, flee, knee, etc.) 8 | b. If the verb ends in ie, change ie to y and add ing 9 | c. For words consisting of consonant-vowel-consonant, double the final 10 | letter before adding ing 11 | d. By default just add ing 12 | 13 | Your task in this exercise is to define a function 14 | make_ing_form()which given a verb in infinitive form 15 | returns its present participle form. Test your function 16 | with words such as lie, see, move and hug. 17 | However, you must not expect such 18 | simple rules to work for all cases 19 | ''' 20 | import string 21 | def make_ing_form(passed_string): 22 | passed_string = passed_string.lower() 23 | letter = list(string.ascii_lowercase) 24 | vowel = ['a','e','i','o','u'] 25 | consonant = [c for c in letter if c not in vowel] 26 | exception = ['be', 'see', 'flee', 'knee', 'lie'] 27 | if passed_string.endswith('e'): 28 | if passed_string in exception: 29 | return passed_string + 'ing' 30 | else: 31 | passed_string = passed_string[:-1] 32 | return passed_string + 'ing' 33 | 34 | elif passed_string.endswith('ie'): 35 | passed_string = passed_string[:-2] 36 | return passed_string + 'ying' 37 | 38 | elif passed_string[-1] in consonant and passed_string[-2] in vowel and passed_string[-3] in consonant: 39 | passed_string += passed_string[-1] 40 | return passed_string + 'ing' 41 | else: 42 | return passed_string + 'ing' 43 | 44 | verb = ['lie', 'see', 'move', 'hug', 'study'] 45 | for item in verb: 46 | print(make_ing_form(item)) 47 | 48 | -------------------------------------------------------------------------------- /problem_26.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Using the higher order function reduce(), write a function 3 | max_in_list()that takes a list of numbers and returns 4 | the largest one. Then ask yourself: why 5 | define and call a new function, when I can just 6 | as well call the reduce() function directly 7 | ''' 8 | 9 | from functools import reduce 10 | 11 | def max_in_list(list_a): 12 | return reduce(lambda a,b: a if (a>b) else b, list_a) 13 | 14 | ab = [5,7,2,4,11,56,32,45,9] 15 | print(max_in_list(ab)) 16 | -------------------------------------------------------------------------------- /problem_27.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program that maps a list of words into a list of 3 | integers representing the lengths of the correponding words. 4 | Write it in three different ways: 5 | 1) using a for-loop, 6 | 2) using the higher order function map() 7 | 3) using list comprehensions 8 | ''' 9 | 10 | 11 | def map_word_with_length_using_for(word_list): 12 | map_word_length = dict() 13 | for item in word_list: 14 | map_word_length[item] = len(item) 15 | return map_word_length 16 | 17 | 18 | ##################################################### 19 | 20 | def map_word_with_length_using_map(word_list): 21 | word_len_list = list(map(lambda x:len(x),word_list)) 22 | return dict(zip(word_list,word_len_list)) 23 | 24 | ##################################################### 25 | 26 | def map_word_with_length_using_list_comprehensions(word_list): 27 | word_len_list = [len(item) for item in word_list] 28 | return dict(zip(word_list, word_len_list)) 29 | 30 | 31 | # list of Shanto's imaginary girlfriends :D 32 | word_list = ['mithila','prokriti','amrita'] 33 | print(map_word_with_length_using_for(word_list)) 34 | print(map_word_with_length_using_map(word_list)) 35 | print(map_word_with_length_using_list_comprehensions(word_list)) 36 | -------------------------------------------------------------------------------- /problem_27_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program that maps a list of words into a list of 3 | integers representing the lengths of the correponding words. 4 | Write it in three different ways: 5 | 1) using a for-loop, 6 | 2) using the higher order function map() 7 | 3) using list comprehensions 8 | ''' 9 | 10 | 11 | def size_of_words_1(list_a): 12 | size = [] 13 | for item in list_a: 14 | count = 0 15 | for i in item: 16 | count += 1 # no need extra for loop 17 | size.append(count) # could be .append(len(item)) 18 | return size 19 | 20 | 21 | ##################################################### 22 | 23 | def size_of_words_2(list_b): 24 | def size(string): 25 | count = 0 26 | for i in string: 27 | count += 1 # no need extra function 28 | return count # shortcut - map(len,list_b) 29 | return list(map(size ,list_b)) # only map doesn't work 30 | # list(map(f,seq)) 31 | 32 | ##################################################### 33 | ##### List comprehension is new to me, gd shortcut :) 34 | 35 | def size_of_words_3(list_c): 36 | return [len(item) for item in list_c] 37 | 38 | 39 | 40 | ab = ['mithila','prokriti','amrita'] 41 | print(size_of_words_1(ab)) 42 | print(size_of_words_2(ab)) 43 | print(size_of_words_3(ab)) 44 | -------------------------------------------------------------------------------- /problem_28.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function find_longest_word()that takes a list of 3 | words and returns the length of the longest one. 4 | Use only higher order functions 5 | ''' 6 | 7 | def find_longest_word(list_a): 8 | return max(list(map(len,list_a))) 9 | 10 | ab = ['cat','meaow','to'] 11 | print(find_longest_word(ab)) 12 | -------------------------------------------------------------------------------- /problem_28_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function find_longest_word()that takes a list of 3 | words and returns the length of the longest one. 4 | Use only higher order functions 5 | ''' 6 | 7 | def find_longest_word(list_a): 8 | return max(list(map(lambda x:len(x),list_a))) 9 | 10 | ab = ['sadswesdf','cat','meaow','to','asdeqw'] 11 | print(find_longest_word(ab)) 12 | -------------------------------------------------------------------------------- /problem_29.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Using the higher order function filter(), define a function 3 | filter_long_words()that takes a list of words and an integer 4 | n and returns the list of words that are longer than n 5 | ''' 6 | 7 | def filter_long_words(list_a,n): 8 | return list(filter(lambda x:len(x)>n, list_a)) 9 | 10 | ab = ['abc','abcd','abcde','abcdef'] 11 | print(filter_long_words(ab,4)) 12 | -------------------------------------------------------------------------------- /problem_30.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Represent a small bilingual lexicon as a Python dictionary 3 | in the following fashion: 4 | 5 | {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", 6 | "new":"nytt", "year":"år"} 7 | 8 | and use it to translate your Christmas cards from 9 | English into Swedish. Use the higher order function map() 10 | to write a function translate()that takes a list of English 11 | words and returns a list of Swedish words. 12 | ''' 13 | 14 | # I added some modification for if there are words not in dic 15 | 16 | def translate(list_a): 17 | dic = {"merry":"god", "christmas":"jul", "and":"och",\ 18 | "happy":"gott","new":"nytt", "year":"år"} 19 | return list(map(lambda x:dic[x] if x in dic else False, list_a)) 20 | # "if dict.get(x)" - would work just fine 21 | # map must return list of same number 22 | # That's why the else part is needed 23 | 24 | 25 | ab = ['merry','and','new','sad'] # 'sad' not in the dictionary 26 | print(translate(ab)) 27 | -------------------------------------------------------------------------------- /problem_30_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Represent a small bilingual lexicon as a Python dictionary 3 | in the following fashion: 4 | 5 | {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", 6 | "new":"nytt", "year":"år"} 7 | 8 | and use it to translate your Christmas cards from 9 | English into Swedish. Use the higher order function map() 10 | to write a function translate()that takes a list of English 11 | words and returns a list of Swedish words. 12 | ''' 13 | 14 | word_map = {"merry":"god", "christmas":"jul", "and":"och",\ 15 | "happy":"gott","new":"nytt", "year":"år"} 16 | 17 | def translate(word_list): 18 | return list(map(lambda x:word_map.get(x) if word_map.get(x)!=None else x,word_list)) 19 | 20 | 21 | word_list = ['merry','and','new','nothing'] # 'nothing' not in the dictionary 22 | print(translate(word_list)) 23 | -------------------------------------------------------------------------------- /problem_31.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement the higher order functions map(), filter()and reduce(). 3 | (They are built-in but writing them yourself 4 | may be a good exercise. 5 | ''' 6 | 7 | def mymap(func,seq): 8 | ini = [] 9 | for item in seq: 10 | ini.append(func(item)) 11 | return ini 12 | 13 | def myfilter(func,seq): 14 | ini = [] 15 | for item in seq: 16 | if func(item)==True: 17 | ini.append(item) 18 | return ini 19 | 20 | def myreduce(func,seq): 21 | i = len(seq) 22 | while i>1: 23 | f = func(seq[0],seq[1]) 24 | seq.pop(0) # "del seq[0]" do so 25 | seq.pop(0) 26 | seq.insert(0,f) 27 | i = len(seq) 28 | return seq[0] 29 | 30 | 31 | ### Copied from net 32 | 33 | def myreduce_net(func, seq): 34 | tmp = seq[0] 35 | for item in seq[1:]: # works with only 'seq' too 36 | tmp = func(tmp,item) 37 | return tmp 38 | 39 | print(mymap(len,['abc','abcd'])) 40 | print(myfilter(lambda x:x>5,[1,3,5,7,9])) 41 | print(myreduce(lambda a,b:a if a>b else b,[3,7,4,5,1])) 42 | print(myreduce_net(lambda a,b:a if a>b else b,[3,7,4,5,1])) 43 | -------------------------------------------------------------------------------- /problem_31_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement the higher order functions map(), filter()and reduce(). 3 | (They are built-in but writing them yourself 4 | may be a good exercise. 5 | ''' 6 | from functools import reduce 7 | def mymap(func,element_list): 8 | return [func(element) for element in element_list] 9 | 10 | element_list = ["this","test","sdk","fingerprint scanner"] 11 | print(mymap(len,element_list)) 12 | #The following is the default map 13 | #print(list(map(len,element_list))) 14 | 15 | def check_odd(a): 16 | return a%2==1 17 | 18 | def myfilter(func, element_list): 19 | return [element for element in element_list if func(element)==True] 20 | 21 | element_list = [21,343,32,11,46] 22 | print(myfilter(check_odd,element_list)) 23 | #The following is the default filter 24 | #print(list(filter(check_odd,element_list))) 25 | 26 | def add(a,b): 27 | return a+b 28 | 29 | def myreduce(func, element_list): 30 | if len(element_list)==0: 31 | return 0 32 | else: 33 | result = element_list[0] 34 | for i in range(1,len(element_list)): 35 | result=func(result,element_list[i]) 36 | return result 37 | 38 | element_list = [1,2,3,4,5,6] 39 | print(myreduce(add,element_list)) 40 | #The following is the default reduce 41 | #print(reduce(add,element_list,0)) 42 | -------------------------------------------------------------------------------- /problem_32.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a version of a palindrome recogniser 3 | that accepts a file name from the 4 | user, reads each line, and prints the line to the screen 5 | if it is a palindrome 6 | ''' 7 | 8 | def palindrome(string): 9 | string = string.lower() 10 | string = string.replace(" ","").replace("\n","") # lines contain '\n' 11 | tem = ['.',',','!','?','\"',"\'"] # in file, need to remove 12 | for i in tem: 13 | string = string.replace(i,"") 14 | tmp='' 15 | length = len(string) 16 | for i in range(length): 17 | tmp += string[length-1] 18 | length -= 1 19 | if string == tmp: 20 | return True 21 | else: 22 | return False 23 | 24 | 25 | print("Enter your filename with extension : ") 26 | file_name = input(">>") 27 | with open(file_name,'r') as f: 28 | for item in f.readlines(): # readlines() create list 29 | print(palindrome(item)) # of all lines till EOF 30 | -------------------------------------------------------------------------------- /problem_32_alternative.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a version of a palindrome recogniser 3 | that accepts a file name from the 4 | user, reads each line, and prints the line to the screen 5 | if it is a palindrome 6 | ''' 7 | import re 8 | def check_palindrome(test_line): 9 | test_line = test_line[:-1] 10 | modify_line = test_line.lower() 11 | # removing all non alpha numeric character using regex 12 | modify_line = re.sub(r"\W+","",modify_line) 13 | if modify_line==modify_line[::-1]: 14 | return test_line 15 | return False 16 | 17 | 18 | print("Enter your filename with extension: ",end="") 19 | file_name = input() 20 | try: 21 | with open(file_name,'r') as f: 22 | for line in f.readlines(): # readlines() create list 23 | check_val = check_palindrome(line) 24 | if check_val != False: 25 | print(check_val) 26 | except: 27 | print(str(file_name)+" not found") 28 | -------------------------------------------------------------------------------- /problem_33.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. 5 | ("Semordnilap" is itself "palindromes" spelled backwards.) Write a semordnilap recogniser that accepts a file 6 | name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilapsto the screen. 7 | For example, if "stressed" and "desserts" is part of the word list, the the output should include 8 | the pair "stressed desserts". Note, by the way, that each pair by itself forms a palindrome! 9 | ''' 10 | import re 11 | #filename = input("Enter filename: ") 12 | filename = "words.txt" 13 | fin = open(filename,"r") 14 | all_lines = fin.readlines() 15 | word_list = set() 16 | word_dict = dict() 17 | for line in all_lines: 18 | line = line[:-1].lower() 19 | words = line.split(" ") 20 | for word in words: 21 | word = re.sub("[^a-zA-Z]+", "", word) 22 | word_list.add(word) 23 | reverse_word = word[::-1] 24 | if reverse_word in word_list: 25 | if reverse_word not in word_dict: 26 | word_dict[word] = reverse_word 27 | 28 | for word in word_dict.keys(): 29 | print(word," ",word_dict[word]) 30 | -------------------------------------------------------------------------------- /problem_34.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | Write a procedure char_freq_table() that, when run in a terminal, 5 | accepts a file name from the user, 6 | builds a frequency listing of the characters contained in the file, 7 | and prints a sorted and nicely formatted character frequency table 8 | to the screen. 9 | ''' 10 | import re 11 | #filename = input("Enter filename: ") 12 | filename = "words.txt" 13 | fin = open(filename,"r") 14 | all_lines = fin.readlines() 15 | char_dict = dict() 16 | for line in all_lines: 17 | line = line[:-1] 18 | words = line.split(" ") 19 | for word in words: 20 | word = re.sub("[^a-zA-Z]+", "", word) 21 | for c in word: 22 | if c in char_dict: 23 | char_dict[c]=char_dict[c]+1 24 | else: 25 | char_dict[c]=1 26 | 27 | sorted_char_dict = sorted(char_dict, key=char_dict.get, reverse=True) 28 | 29 | for c in sorted_char_dict: 30 | print(c," ",char_dict[c]) 31 | -------------------------------------------------------------------------------- /problem_35.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | The International Civil Aviation Organization (ICAO) alphabet assigns code words to the letters of the English alphabet acrophonically (Alfa for A, Bravo for B, etc.) so that critical combinations of letters (and numbers) can be pronounced and understood by those who transmit and receive voice messages by radio or telephone regardless of their native language, especially when the safety of navigation or persons is essential. Here is a Python dictionary covering 5 | one version of the ICAO alphabet: 6 | Your task in this exercise is to write a procedure speak_ICAO() 7 | able to translate any text (i.e. any string) into spoken ICAO words. 8 | You need to import at least two libraries: os and time. 9 | On a mac, you have access to the system TTS (Text-To-Speech) as follows: 10 | os.system('say ' + msg), where msg is the string to be spoken. 11 | (Under UNIX/Linux and Windows, something similar might exist.) 12 | Apart from the text to be spoken, your procedure also needs to accept 13 | two additional parameters: a float indicating the length of the pause 14 | between each spoken ICAO word, and a float indicating the length of the 15 | pause between each word spoken. 16 | ''' 17 | ''' 18 | I am not showing how to sound. Just representing it as text 19 | ''' 20 | import os, time, re 21 | #original_message = input("Enter a line: ") 22 | message = "Hello Shovon" 23 | 24 | d = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot', 25 | 'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima', 26 | 'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo', 27 | 's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey', 28 | 'x':'x-ray', 'y':'yankee', 'z':'zulu'} 29 | 30 | def icao(message, char_pause, word_pause): 31 | word_list = re.findall('\w+',message) 32 | for word in word_list: 33 | word = word.lower() 34 | for c in word: 35 | if c in d: 36 | icao_word = d[c] 37 | print(icao_word+char_pause,end="") 38 | print(word_pause,end="") 39 | icao(message," "," ") 40 | -------------------------------------------------------------------------------- /problem_36.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | A hapax legomenon (often abbreviated to hapax) is a word which occurs 5 | only once in either the written 6 | record of a language, the works of an author, 7 | or in a single text. Define a function that given the file name of 8 | a text will return all its hapaxes. 9 | Make sure your program ignores capitalization.''' 10 | 11 | import re 12 | #filename = input("Enter a line: ") 13 | filename = "words.txt" 14 | fin = open(filename,"r") 15 | lines = fin.readlines() 16 | word_dict = dict() 17 | for line in lines: 18 | word_list = re.findall('\w+',line) 19 | for word in word_list: 20 | word = word.lower() 21 | if word in word_dict: 22 | word_dict[word]=word_dict[word]+1 23 | else: 24 | word_dict[word]=1 25 | 26 | for word in word_dict: 27 | if word_dict[word] == 1: 28 | print(word) 29 | -------------------------------------------------------------------------------- /problem_37.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Statement: 3 | ====================== 4 | Write a program that given a text file will 5 | create a new text file in which all the lines from the original file are 6 | numbered from 1 to n (where n is the number of lines in the file) 7 | ''' 8 | 9 | 10 | #filename = input("Enter a line: ") 11 | filename = "test.txt" 12 | output_filename = "test_numbered.txt" 13 | fin = open(filename,"r") 14 | fout = open(output_filename,"w") 15 | lines = fin.readlines() 16 | word_dict = dict() 17 | cnt = 0 18 | for line in lines: 19 | cnt+=1 20 | output_line = str(cnt)+". "+line 21 | fout.write(output_line) 22 | 23 | print("Lines are numbered. Check: "+output_filename) 24 | fin.close() 25 | fout.close() 26 | -------------------------------------------------------------------------------- /test.txt: -------------------------------------------------------------------------------- 1 | Go hang a salami I'm a lasagna hog 2 | Was it a rat I saw? 3 | Step on no pets 4 | Sit on a potato pan, Otis 5 | Lisa Bonet ate no basil 6 | Satan, oscillate my metallic sonatas 7 | I roamed under it as a tired nude Maori 8 | Rise to vote sir 9 | Dammit, I'm mad! 10 | Ahmedur Rahman Shovon is not a palindrome 11 | noyon 12 | shanto -------------------------------------------------------------------------------- /test_numbered.txt: -------------------------------------------------------------------------------- 1 | 1. Go hang a salami I'm a lasagna hog 2 | 2. Was it a rat I saw? 3 | 3. Step on no pets 4 | 4. Sit on a potato pan, Otis 5 | 5. Lisa Bonet ate no basil 6 | 6. Satan, oscillate my metallic sonatas 7 | 7. I roamed under it as a tired nude Maori 8 | 8. Rise to vote sir 9 | 9. Dammit, I'm mad! 10 | 10. Ahmedur Rahman Shovon is not a palindrome 11 | 11. noyon 12 | 12. shanto -------------------------------------------------------------------------------- /words.txt: -------------------------------------------------------------------------------- 1 | According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. 2 | ("Semordnilap" is itself "palindromes" spelled backwards.) Write a semordnilap recogniser that accepts a file 3 | name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilapsto the screen. 4 | For example, if "stressed" and "desserts" is part of the word list, the the output should include 5 | the pair "stressed desserts". Note, by the way, that each pair by itself forms a palindrome! 6 | --------------------------------------------------------------------------------