├── .gitignore ├── 01.py ├── 02.py ├── 03.py ├── 04.py ├── 05.py ├── 06.py ├── 07.py ├── 08.py ├── 09.py ├── 10.py ├── 11.py ├── 12.py ├── 13.py ├── 14.py ├── 15.py ├── 16.py ├── 17.py ├── 18.py ├── 19.py ├── 20.py ├── 21.py ├── 22.py ├── 23.py ├── 24.py ├── 25.py ├── 26.py ├── 27.py ├── 28.py ├── 29.py ├── 30.py ├── 31.py ├── 32.py ├── 32.txt ├── 33.py ├── 33.txt ├── 34.py ├── 34.txt ├── 35.py ├── 36.py ├── 36.txt ├── 37.py ├── 37.txt ├── 37_out.txt ├── 38.py ├── 38.txt ├── 39.py ├── 40.py ├── 41.py ├── 42.py ├── 43.py ├── 44.py ├── 45.py ├── 46.py ├── 47. Code Jam.py ├── 48. Gmail Bomb.py ├── 49. Fb_bomb.py ├── 50. Youtube_downloader.py ├── LICENSE ├── README.md ├── numbered_sample_text.txt ├── sample text.txt └── sample_text.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | -------------------------------------------------------------------------------- /01.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function max() that takes two numbers as arguments and returns 3 | the largest of them. Use the if-then-else construct available in Python. 4 | (It is true that Python has the max() function built in, but writing it 5 | yourself is nevertheless a good exercise.) 6 | ''' 7 | 8 | def max1(m,n): 9 | if m>n: 10 | return m 11 | else: 12 | return n 13 | 14 | print max1(6,5) 15 | -------------------------------------------------------------------------------- /02.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function max_of_three() that takes three numbers as 3 | arguments and returns the largest of them. 4 | ''' 5 | 6 | def max_of_three(a,b,c): 7 | if a>b and a>c: 8 | print a 9 | elif b>c: 10 | print b 11 | else: 12 | print c 13 | 14 | print max_of_three(0,15,2) -------------------------------------------------------------------------------- /03.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function that computes the length of a given list or string. 3 | (It is true that Python has the len() function built in, 4 | but writing it yourself is nevertheless a good exercise.) 5 | ''' 6 | 7 | a = 'abd' 8 | 9 | def length(x): 10 | c=0 11 | for _ in a: 12 | c = c +1 13 | return c 14 | 15 | print length(a) -------------------------------------------------------------------------------- /04.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function that takes a character 3 | i.e. a string of length 1) and returns True if 4 | it is a vowel, False otherwise. 5 | ''' 6 | 7 | def vowel(x): 8 | if x in ('aeiou'): 9 | return True 10 | else: 11 | return False 12 | 13 | 14 | print vowel('b') -------------------------------------------------------------------------------- /05.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/garg10may/Python-for-Beginners-Solve-50-Exercises-Live/7390f13809a4083169a9a7b7c4c6bbebc05bad04/05.py -------------------------------------------------------------------------------- /06.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function sum() and a function multiply() that sums and multiplies 3 | (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) 4 | should return 10, and multiply([1, 2, 3, 4]) should return 24. 5 | ''' 6 | 7 | 8 | def sum1(x): 9 | c=0 10 | for i in x: 11 | c += i 12 | return c 13 | 14 | print sum1([1, 2, 3, 4]) 15 | 16 | 17 | def multiply(x): 18 | c=1 19 | for i in x: 20 | c *= i 21 | return c 22 | 23 | print multiply([1, 2, 3, 4]) 24 | -------------------------------------------------------------------------------- /07.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function reverse() that computes the reversal of a string. 3 | For example, reverse("I am testing") 4 | should return the string "gnitset ma I". 5 | ''' 6 | 7 | def reverse(x): 8 | new =[] 9 | for i in range(len(x))[::-1]: 10 | new.append(x[i]) 11 | print ''.join(new) 12 | 13 | reverse('I am testing') -------------------------------------------------------------------------------- /08.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function is_palindrome() that recognizes palindromes 3 | (i.e. words that look the same written backwards). For example, 4 | is_palindrome("radar") should return True. 5 | ''' 6 | 7 | def is_palindrome(x): 8 | if x == x[::-1]: 9 | print True 10 | else: 11 | print False 12 | 13 | is_palindrome("aradar") -------------------------------------------------------------------------------- /09.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, 3 | and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, 4 | but for the sake of the exercise you should pretend Python did not have this operator.) 5 | ''' 6 | 7 | 8 | def is_member(x, a): 9 | if x in a: 10 | print True 11 | else: 12 | print False 13 | 14 | def is_member2(x,a): 15 | status =0 16 | for i in a: 17 | if x==i: 18 | print True 19 | status =1 20 | if status ==0: 21 | print False 22 | 23 | is_member('c',['a',1,2,3,'b']) 24 | is_member2('a',['a',1,2,3,'b']) -------------------------------------------------------------------------------- /10.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function overlapping() that takes two lists and returns True if they have at least one member in common, 3 | False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, 4 | you should (also) write it using two nested for-loops. 5 | ''' 6 | 7 | def overlapping(m,n): 8 | l1 =len(m) 9 | l2 = len(n) 10 | for i in range(l1): 11 | for j in range(l2): 12 | if m[i]==n[j]: 13 | status =1 14 | break 15 | else: 16 | status =0 17 | if status ==1: 18 | print True 19 | else: 20 | print False 21 | 22 | 23 | overlapping(['a','e'], ['c','d']) -------------------------------------------------------------------------------- /11.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a function generate_n_chars() that takes an integer n and a character c and returns a string, 3 | n characters long, consisting only of c:s. For example, generate_n_chars(5,"x") should return the string "xxxxx". 4 | (Python is unusual in that you can actually write an expression 5 * "x" that will evaluate to "xxxxx". 5 | For the sake of the exercise you should ignore that the problem can be solved in this manner.) 6 | ''' 7 | 8 | 9 | def generate_n_chars(n,x): 10 | k=[] 11 | for i in range(n): 12 | k.append(x) 13 | print ''.join(k) 14 | 15 | generate_n_chars( 5, 't') 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /12.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. 3 | For example, histogram([4, 9, 7]) should print the following: 4 | 5 | **** 6 | ********* 7 | ******* 8 | 9 | 10 | ''' 11 | 12 | def histogram(x): 13 | for i in x: 14 | print i * '*' 15 | 16 | histogram([4,9,7]) -------------------------------------------------------------------------------- /13.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The function max() from exercise 1) and the function max_of_three() from exercise 2) will only work for two and three numbers, 3 | respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? 4 | Write a function max_in_list() that takes a list of numbers and returns the largest one. 5 | ''' 6 | 7 | def max1(l): 8 | max =0 9 | for i in range(len(l)-1): 10 | if l[i] > l[i+1] and l[i]>max: 11 | max = l[i] 12 | elif l[i+1]>max: 13 | max = l[i+1] 14 | print max 15 | 16 | 17 | max1([1,2,34,4,6,345]) -------------------------------------------------------------------------------- /14.py: -------------------------------------------------------------------------------- 1 | '''Write a program that maps a list of words into a list of integers representing the lengths of the corresponding words.''' 2 | 3 | 4 | def maps(x): 5 | k=[] 6 | for i in x: 7 | k.append(len(i)) 8 | print k 9 | 10 | 11 | maps(['apple','orange','cat']) 12 | l = ['apple','orange','cat'] 13 | print map( len, l) 14 | -------------------------------------------------------------------------------- /15.py: -------------------------------------------------------------------------------- 1 | '''Write a function find_longest_word() that takes a list of words and returns the length of the longest one.''' 2 | 3 | def maps(x): 4 | k=[] 5 | for i in x: 6 | k.append(len(i)) 7 | print max(k) 8 | 9 | 10 | maps(['apple','orange','cat']) -------------------------------------------------------------------------------- /16.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function filter_long_words() that takes a list of words 3 | and an integer n and returns the list of words that are longer than n. 4 | ''' 5 | 6 | def filter_long_words(x,n): 7 | k=[] 8 | for i in x: 9 | if len(i)>n: 10 | k.append(i) 11 | print k 12 | 13 | 14 | filter_long_words(['apple','orange','cat'], 4) -------------------------------------------------------------------------------- /17.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a version of a palindrome recognizer that also accepts phrase palindromes such as 3 | "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", 4 | "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", 5 | "Rise to vote sir", or the exclamation "Dammit, I'm mad!". 6 | Note that punctuation, capitalization, and spacing are usually ignored. 7 | ''' 8 | 9 | 10 | def palindrome(x): 11 | l=[] 12 | for i in x: 13 | if i.isalpha(): 14 | l.append(i.lower()) 15 | print ''.join(l) 16 | if l==l[::-1]: 17 | print 'palindrome' 18 | else: 19 | print 'Not a palindrome' 20 | 21 | palindrome("Go hang a salami I'm a lasagna hog.") -------------------------------------------------------------------------------- /18.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: 3 | The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence 4 | to see if it is a pangram or not. 5 | ''' 6 | 7 | import string 8 | 9 | def pangram(x): 10 | for i in string.letters[:26]: 11 | if i in x.lower(): 12 | status =1 13 | else: 14 | print 'not a pangram' 15 | status =0 16 | break 17 | 18 | if status==1: 19 | print 'pangram' 20 | 21 | pangram('The q brown fox jumps over the lazy dog') 22 | 23 | -------------------------------------------------------------------------------- /19.py: -------------------------------------------------------------------------------- 1 | ''' 2 | "99 Bottles of Beer" is a traditional song in the United States and Canada. 3 | It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, 4 | and can take a long time to sing. The song's 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 singers reach zero. 8 | Your task here is write a Python program capable of generating all the verses of the song. 9 | ''' 10 | 11 | def song(): 12 | print '99 bottles of beer on the wall, 99 bottles of beer' 13 | for i in range(99)[::-1]: 14 | print 'Take one down, pass it around,' + str(i) + ' bottles of beer on the wall.' 15 | 16 | song() -------------------------------------------------------------------------------- /20.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Represent a small bilingual lexicon as a Python dictionary in the following fashion 3 | {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ar"} 4 | and use it to translate your Christmas cards from English into Swedish. 5 | That is, write a function translate() that takes a list of English words and returns a list of Swedish words. 6 | ''' 7 | 8 | def tanslate(x): 9 | new=[] 10 | d = {"merry":"god", 11 | "christmas":"jul", 12 | "and":"och", 13 | "happy":"gott", 14 | "new":"nytt", 15 | "year":"ar"} 16 | l = x.split(' ') 17 | for i in l: 18 | new.append(d[i]) 19 | print new 20 | print ' '.join(new) 21 | 22 | tanslate('merry christmas and happy new year') 23 | -------------------------------------------------------------------------------- /21.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. 3 | Represent the frequency listing as a Python dictionary. 4 | Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab"). 5 | ''' 6 | 7 | 8 | def char_freq(x): 9 | d ={} 10 | for i in x: 11 | d[i] = d.get(i,0) +1 12 | print d 13 | 14 | 15 | char_freq("abbabcbdba.#$Fbdbdbabababcbcbab") 16 | 17 | 18 | -------------------------------------------------------------------------------- /22.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a 3 | letter some fixed number of positions down the alphabet. For example, 4 | with a shift of 3, A would be replaced by D, B would become E, and so on. 5 | The method is named after Julius Caesar, who used it to communicate with his generals. 6 | ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. 7 | In Python, the key for ROT-13 may be represented by means of the following dictionary: 8 | 9 | key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 10 | 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 11 | 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 12 | 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 13 | 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 14 | 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 15 | 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'} 16 | Your task in this exercise is to implement an encoder/decoder of ROT-13. 17 | Once you're done, you will be able to read the following secret message: 18 | 19 | Pnrfne pvcure? V zhpu cersre Pnrfne fnynq! 20 | Note that since English has 26 characters, your ROT-13 program will be able to both encode and decode texts written in English. 21 | ''' 22 | 23 | 24 | def rot_decoder(x): 25 | new =[] 26 | d = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 27 | 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 28 | 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 29 | 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 30 | 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 31 | 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 32 | 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'} 33 | for i in x: 34 | new.append(d.get(i,i)) 35 | print ''.join(new) 36 | 37 | rot_decoder('Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!') 38 | 39 | # Our decoder function can also encode the message since we have 26 characters. But in case if isn't you can use below strategy. 40 | def rot_encoder(x): 41 | key_inverse = { v:k for k,v in d.items()} 42 | for i in x: 43 | new.append(d.get(i,i)) 44 | print ''.join(new) 45 | 46 | rot_decoder('Caesar cipher? I much prefer Caesar salad!') 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /23.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a simple "spelling correction" function correct() that takes a string and sees to it that 3 | 1) two or more occurrences of the space character is compressed into one, and 4 | 2) inserts an extra space after a period if the period is directly followed by a letter. 5 | E.g. correct("This is very funny and cool.Indeed!") should return "This is very funny and cool. Indeed!" 6 | Tip: Use regular expressions! 7 | ''' 8 | 9 | import re 10 | 11 | def correct(x): 12 | x =x.replace('.', '. ') 13 | x = re.sub(' +', ' ', x) 14 | print x 15 | 16 | correct ("This is very funny and cool.Indeed!") 17 | 18 | 19 | -------------------------------------------------------------------------------- /24.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The third person singular verb form in English is distinguished by the suffix -s, 3 | which is added to the stem of the infinitive form: run -> runs. 4 | A simple set of rules can be given as follows: 5 | If the verb ends in y, remove it and add ies 6 | If the verb ends in o, ch, s, sh, x or z, add es 7 | By default just add s 8 | Your task in this exercise is to define a function make_3sg_form() which given a verb in infinitive 9 | form returns its third person singular form. Test your function with words like try, brush, run and fix. 10 | Note however that the rules must be regarded as heuristic, in the sense that you must not expect them to work for all cases. 11 | Tip: Check out the string method endswith(). 12 | ''' 13 | 14 | def make_3sg_form(x): 15 | if x.endswith('y'): 16 | x = x[:-1] + 'ies' 17 | elif x.endswith( ('o', 'ch', 's', 'sh', 'x', 'z')): 18 | x += 'es' 19 | else: 20 | x += 's' 21 | print x 22 | 23 | make_3sg_form('fix') 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /25.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In English, the present participle is formed by adding the suffix -ing to the infinite form: go -> going. 3 | A simple set of heuristic rules can be given as follows: 4 | If the verb ends in e, drop the e and add ing (if not exception: be, see, flee, knee, etc.) 5 | If the verb ends in ie, change ie to y and add ing 6 | For words consisting of consonant-vowel-consonant, double the final letter before adding ing 7 | By default just add ing 8 | Your task in this exercise is to define a function make_ing_form() which given a verb in infinitive form 9 | returns its present participle form. 10 | Test your function with words such as lie, see, move and hug. 11 | However, you must not expect such simple rules to work for all cases. 12 | ''' 13 | 14 | def make_ing_form(x): 15 | if x.endswith('e') and not x.endswith('ie') and not x.endswith('ee') and not len(x)==2: 16 | x = x[:-1] + 'ing' 17 | elif x.endswith('ie'): 18 | x = x[:-2] + 'ying' 19 | elif len(x)==3 and x[-2] in ('aeiou') and x[-1] not in ('aeiou') and x[-3] not in ('aeiou'): 20 | x += x[-1] + 'ing' 21 | else: 22 | x += 'ing' 23 | print x 24 | make_ing_form('flee') 25 | -------------------------------------------------------------------------------- /26.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Using the higher order function reduce(), write a function max_in_list() that takes a list of numbers 3 | and returns the largest one. Then ask yourself: why define and call a new function, 4 | when I can just as well call the reduce() function directly? 5 | ''' 6 | 7 | 8 | def max_in_list(l): 9 | largest = reduce( lambda x,y: max(x,y) , l) 10 | return largest 11 | 12 | l = [1,2,3,78,34,90,36,9] 13 | 14 | print max_in_list(l) 15 | 16 | 17 | print reduce( max , l) 18 | 19 | -------------------------------------------------------------------------------- /27.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program that maps a list of words into a list of integers representing the lengths of the correponding words. 3 | Write it in three different ways: 4 | 1) using a for-loop, 5 | 2) using the higher order function map(), and 6 | 3) using list comprehensions. 7 | ''' 8 | 9 | # already done 10 | 11 | #2 12 | l = ['apple', 'orange', 'cat'] 13 | print map( lambda x : len(x), l) 14 | 15 | print map( len, l) 16 | 17 | #3 18 | print [ len(i) for i in l] 19 | 20 | -------------------------------------------------------------------------------- /28.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function find_longest_word() that takes a list of words and returns the length of the longest one. 3 | Use only higher order functions. 4 | ''' 5 | 6 | 7 | l = ['apple', 'orange', 'cat'] 8 | print max(map( len, l)) -------------------------------------------------------------------------------- /29.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Using the higher order function filter(), define a function filter_long_words() 3 | that takes a list of words and an integer n and returns the list of words that are longer than n 4 | ''' 5 | 6 | n=2 7 | x = ['abc','b','adfadfasd'] 8 | print filter(lambda x: len(x)>n, x) 9 | 10 | 11 | -------------------------------------------------------------------------------- /30.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Represent a small bilingual lexicon as a Python dictionary in the following fashion 3 | {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"ar"} 4 | and use it to translate your Christmas cards from English into Swedish. Use the higher order function map() 5 | to write a function translate() that takes a list of English words and returns a list of Swedish words. 6 | ''' 7 | 8 | def translate(x): 9 | d ={"merry":"god", 10 | "christmas":"jul", 11 | "and":"och", 12 | "happy":"gott", 13 | "new":"nytt", 14 | "year":"ar"} 15 | l = x.split() 16 | print map ( lambda x: d[x], l) 17 | 18 | 19 | translate("merry new christmas and happy new year") 20 | -------------------------------------------------------------------------------- /31.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement the higher order functions map(), filter() and reduce(). 3 | (They are built-in but writing them yourself may be a good exercise.) 4 | ''' 5 | 6 | def map1(f, l): 7 | new=[] 8 | for i in l: 9 | new.append(f(i)) 10 | return new 11 | 12 | 13 | def filter1(f, l): 14 | new =[] 15 | for i in l: 16 | if f(i) == True: 17 | new.append(i) 18 | return new 19 | 20 | def reduce1(f, l): 21 | new = l[0] 22 | for i in l[1:]: 23 | new = f(new, i) 24 | return new 25 | 26 | print reduce1(max, [1,2,-45,3,0]) 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /32.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a version of a palindrome recogniser that accepts a 3 | file name from the user, reads each line, and prints the line to the screen 4 | if it is a palindrome. 5 | ''' 6 | 7 | 8 | def palindrome1(x): 9 | for i in open(x).read().split('\n'): 10 | if i==i[::-1]: 11 | print i + " is palindrome" 12 | 13 | 14 | palindrome1('32.txt') 15 | 16 | 17 | def palindrome2(x): 18 | for i in open(x).readlines(): 19 | i = i.rstrip() 20 | if i==i[::-1]: 21 | print i + " is palindrome" 22 | 23 | palindrome2('32.txt') 24 | -------------------------------------------------------------------------------- /32.txt: -------------------------------------------------------------------------------- 1 | abc 2 | cat 3 | bananna 4 | abcba 5 | 121 6 | palindromes 7 | dollar 8 | abcdcba 9 | semordnilap 10 | -------------------------------------------------------------------------------- /33.py: -------------------------------------------------------------------------------- 1 | ''' 2 | According to Wikipedia, a semordnilap is a word or phrase that spells a different 3 | word or phrase backwards. ("Semordnilap" is itself "palindromes" spelled backwards.) 4 | Write a semordnilap recogniser that accepts a file name (pointing to a list of words) 5 | from the user and finds and prints all pairs of words that are semordnilaps to the screen. 6 | For example, if "stressed" and "desserts" is part of the word list, the the output 7 | should include the pair "stressed desserts". Note, by the way, that each pair by itself 8 | forms a palindrome! 9 | ''' 10 | 11 | def semordnilap(x): 12 | f = open(x).read() 13 | words = f.split('\n') 14 | while words: 15 | a = words[0] 16 | words.remove(a) 17 | if a[::-1] in words: 18 | print a + ' and ' + a[::-1] + ' are semordnilap' 19 | 20 | semordnilap('33.txt') -------------------------------------------------------------------------------- /33.txt: -------------------------------------------------------------------------------- 1 | abc 2 | cat 3 | bananna 4 | abcba 5 | 121 6 | palindromes 7 | dollar 8 | abcdcba 9 | semordnilap 10 | tac 11 | stressed 12 | desserts -------------------------------------------------------------------------------- /34.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a procedure char_freq_table() that, when run in a terminal, accepts a file name 3 | from the user, builds a frequency listing of the characters contained in the file, and 4 | prints a sorted and nicely formatted character frequency table to the screen. 5 | ''' 6 | 7 | 8 | example = __import__('21') 9 | 10 | def char_freq_table(): 11 | n = raw_input('Please enter a file name: ') 12 | example.char_freq(open(n).read()) 13 | 14 | 15 | char_freq_table() 16 | -------------------------------------------------------------------------------- /34.txt: -------------------------------------------------------------------------------- 1 | aaaaaaacccccccbcccccc4444444 -------------------------------------------------------------------------------- /35.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The International Civil Aviation Organization (ICAO) alphabet assigns code words to the letters 3 | of the English alphabet acrophonically (Alfa for A, Bravo for B, etc.) so that critical combinations 4 | of letters (and numbers) can be pronounced and understood by those who transmit and receive voice 5 | messages by radio or telephone regardless of their native language, especially when the safety of 6 | navigation or persons is essential. Here is a Python dictionary covering one version of the ICAO alphabet: 7 | 8 | d = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot', 9 | 'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima', 10 | 'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo', 11 | 's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey', 12 | 'x':'x-ray', 'y':'yankee', 'z':'zulu'} 13 | 14 | Your task in this exercise is to write a procedure speak_ICAO() able to translate any text 15 | (i.e. any string) into spoken ICAO words. You need to import at least two libraries: os and time. 16 | On a mac, you have access to the system TTS (Text-To-Speech) as follows: os.system('say ' + msg), 17 | where msg is the string to be spoken. (Under UNIX/Linux and Windows, something similar might exist.) 18 | Apart from the text to be spoken, your procedure also needs to accept two additional parameters: 19 | a float indicating the length of the pause between each spoken ICAO word, and a float indicating 20 | the length of the pause between each word spoken. 21 | ''' 22 | 23 | import pyttsx 24 | 25 | def speak_ICAO(x): 26 | d = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot', 27 | 'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima', 28 | 'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo', 29 | 's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey', 30 | 'x':'x-ray', 'y':'yankee', 'z':'zulu'} 31 | engine = pyttsx.init() 32 | for i in x.lower(): 33 | engine.say(d.get(i,i)) 34 | engine.runAndWait() 35 | 36 | speak_ICAO('Move Left') 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /36.py: -------------------------------------------------------------------------------- 1 | """ 2 | A hapax legomenon (often abbreviated to hapax) is a word which occurs only once in either the written record of a 3 | language, the works of an author, or in a single text. Define a function that given the file name of a text will return 4 | all its hapaxes. Make sure your program ignores capitalization. 5 | """ 6 | import re 7 | 8 | def hapax(x): 9 | d={} 10 | f = open(x) 11 | for word in re.findall('\w+', f.read().lower()): 12 | d[word] = d.get(word,0) + 1 13 | f.close() 14 | print [ k for k, v in d.items() if v==1] 15 | 16 | hapax('36.txt') 17 | 18 | 19 | -------------------------------------------------------------------------------- /36.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque venenatis arcu quis egestas euismod. Donec sed dolor urna. Integer auctor dui ex, eget hendrerit dui ultricies ac. Fusce at tempor nibh, non dictum urna. Suspendisse mattis nibh eget dictum ornare. Curabitur ex justo, ultrices vitae scelerisque eget, pretium tincidunt nibh. Fusce porttitor sit amet eros eget auctor. Etiam sed tortor euismod, feugiat tortor ut, placerat quam. Mauris quis nisi a felis semper faucibus nec eget arcu. Nullam aliquam felis libero, nec fermentum sapien mollis nec. Etiam at nunc vitae urna scelerisque tristique. 2 | 3 | Aenean ultrices nunc ac dignissim hendrerit. Integer tincidunt rutrum dapibus. Suspendisse vulputate ac arcu ac pulvinar. Ut at egestas neque. Nunc diam velit, mollis eget justo nec, mollis feugiat dui. Mauris semper, lacus ac sodales tincidunt, diam arcu suscipit velit, vel malesuada sem nunc id nisi. Sed cursus, augue eget maximus tempus, nisl leo posuere nunc, eu imperdiet leo ipsum at leo. 4 | 5 | Praesent et risus eu leo tempus pharetra. Nulla in sapien quis neque tristique pharetra. Nunc in dictum dolor. Donec cursus diam sit amet fringilla pellentesque. Suspendisse vel ante accumsan, porttitor diam vel, imperdiet risus. Mauris convallis eleifend arcu euismod facilisis. Nulla volutpat odio vel lacus ornare hendrerit. Sed posuere mauris egestas turpis fringilla, sed pulvinar mi porttitor. Integer quis felis porttitor turpis mattis egestas non eu mauris. 6 | 7 | Vestibulum vel dolor et orci viverra commodo vitae quis risus. Morbi bibendum nibh vitae enim sodales cursus. Nulla facilisi. Duis nulla nibh, porta sed magna non, efficitur fringilla enim. Donec sed ipsum pharetra, laoreet dui vel, elementum ex. In nec mi eget ligula commodo congue vitae in risus. Suspendisse rhoncus sapien non placerat hendrerit. Sed volutpat et odio at cursus. 8 | 9 | Etiam sit amet tellus in enim condimentum luctus ut vitae diam. Ut eu tincidunt dui. Phasellus a mattis mauris. Integer blandit enim eget nisl scelerisque vulputate. Mauris ultricies auctor pellentesque. Vivamus lacinia condimentum maximus. Mauris sed ipsum id felis ullamcorper semper. In volutpat, sapien ut maximus ultrices, eros tellus euismod enim, vitae porta nisi tellus at est. In in dictum mi. Nunc finibus neque enim, vitae lobortis lacus sodales eu. Maecenas rhoncus viverra nisi vitae vulputate. Curabitur vel porttitor neque. Aliquam ut fringilla lorem. Pellentesque nec urna posuere, ullamcorper libero quis, consequat quam. -------------------------------------------------------------------------------- /37.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program that given a text file will create a new text file in which all the lines 3 | from the original file are numbered from 1 to n 4 | (where n is the number of lines in the file). 5 | ''' 6 | 7 | f = open('37.txt') 8 | 9 | f_out = open('37_out.txt', 'w') 10 | 11 | count =1 12 | for i in f: 13 | print i 14 | f_out.write(str(count) + '. ' + i) 15 | count +=1 16 | 17 | f.close() 18 | f_out.close() 19 | 20 | -------------------------------------------------------------------------------- /37.txt: -------------------------------------------------------------------------------- 1 | apple 2 | banana 3 | cat 4 | dog 5 | elephant 6 | -------------------------------------------------------------------------------- /37_out.txt: -------------------------------------------------------------------------------- 1 | 1. apple 2 | 2. banana 3 | 3. cat 4 | 4. dog 5 | 5. elephant 6 | -------------------------------------------------------------------------------- /38.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program that will calculate the average word length of a text stored in a file 3 | ( i.e. the sum of all the lengths of the word tokens in the text, divided by the number 4 | of word tokens). 5 | ''' 6 | import re 7 | 8 | def avg_length(x): 9 | count = 0.0 10 | f = open(x) 11 | words = re.findall('\w+', f.read()) 12 | for word in words: 13 | count += len(word) 14 | return count/len(words) 15 | 16 | print avg_length('38.txt') -------------------------------------------------------------------------------- /38.txt: -------------------------------------------------------------------------------- 1 | abc def fgh tgh wert sdfgh -------------------------------------------------------------------------------- /39.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | ''' 3 | Write a program able to play the "Guess the number"-game, where the number to be guessed is randomly chosen between 1 and 20. 4 | (Source: http://inventwithpython.com) This is how it should work when run in a terminal: 5 | >>> import guess_number 6 | Hello! What is your name? 7 | Torbj�rn 8 | Well, Torbj�rn, I am thinking of a number between 1 and 20. 9 | Take a guess. 10 | 10 11 | Your guess is too low. 12 | Take a guess. 13 | 15 14 | Your guess is too low. 15 | Take a guess. 16 | 18 17 | Good job, Torbj�rn! You guessed my number in 3 guesses! 18 | ''' 19 | 20 | # Method 1 - using while loop 21 | import random 22 | 23 | name = raw_input("Hello! What is your name?\n") 24 | print "Well, " + name + ", I am thinking of a number between 1 and 20" 25 | no = random.randint(1,20) 26 | guess = int(raw_input("Take a guess\n")) 27 | count =1 28 | 29 | while guess != no: 30 | if guess < no: 31 | print "Your guess is too low." 32 | if guess > no: 33 | print "Your guess is too high" 34 | count +=1 35 | guess = int(raw_input("Take a guess\n")) 36 | 37 | print "Good job, %s! You guessed my number in %d guesses!" % (name ,count) 38 | 39 | 40 | #Method 2 using recursion. Here global makes count available to local scope of your function. 41 | import random 42 | 43 | def check(): 44 | global count 45 | guess = int(raw_input("Take a guess\n")) 46 | if guess == no: 47 | print "Good job, %s! You guessed my number in %d guesses!" %(name,count) 48 | if guess < no: 49 | print "Your guess is too low." 50 | count +=1 51 | check() 52 | if guess > no: 53 | print "Your guess is too high" 54 | count +=1 55 | check() 56 | 57 | name = raw_input("Hello! What is your name?\n") 58 | print "Well, " + name + ", I am thinking of a number between 1 and 20" 59 | no = random.randint(1,20) 60 | print no 61 | global count 62 | count =1 63 | check() -------------------------------------------------------------------------------- /40.py: -------------------------------------------------------------------------------- 1 | ''' 2 | An anagram is a type of word play, the result of rearranging the letters of a word or phrase to 3 | produce a new word or phrase, using all the original letters exactly once; e.g., orchestra = carthorse, 4 | A decimal point = I'm a dot in place. Write a Python program that, when started 5 | 1) randomly picks a word w from given list of words, 6 | 2) randomly permutes w (thus creating an anagram of w), 7 | 3) presents the anagram to the user, and 8 | 4) enters an interactive loop in which the user is invited to guess the original word. 9 | It may be a good idea to work with (say) colour words only. The interaction with the program may look like so: 10 | 11 | >>> import anagram 12 | Colour word anagram: onwbr 13 | Guess the colour word! 14 | black 15 | Guess the colour word! 16 | brown 17 | Correct! 18 | ''' 19 | 20 | 21 | import random 22 | import itertools 23 | 24 | def anagram(x): 25 | l=[] 26 | word = random.choice(x) 27 | anagrams = itertools.permutations(word) 28 | for i in anagrams: 29 | l.append(''.join(i)) 30 | anagram = random.choice(l) #again randomly choose the anagram otherwise it would always contain the last permutation 31 | print 'Colour word anagram: %s' %anagram 32 | guess = raw_input('Guess the colour word!\n') 33 | while guess!=word: 34 | guess = raw_input('Guess the colour word!\n') 35 | print 'Correct!' 36 | 37 | anagram(['blue','red','orange','violet','yellow','black','green']) 38 | 39 | 40 | -------------------------------------------------------------------------------- /41.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In a game of Lingo, there is a hidden word, five characters long. The object of the game is to find this 3 | word by guessing, and in return receive two kinds of clues: 4 | 1) the characters that are fully correct, with respect to identity as well as to position, and 5 | 2) the characters that are indeed present in the word, but which are placed in the wrong position. 6 | Write a program with which one can play Lingo. Use square brackets to mark characters correct in the sense of 7 | 1), and ordinary parentheses to mark characters correct in the sense of 8 | 2). Assuming, for example, that the program conceals the word "tiger", 9 | you should be able to interact with it in the following way: 10 | 11 | >>> import lingo 12 | snake 13 | Clue: snak(e) 14 | fiest 15 | Clue: f[i](e)s(t) 16 | times 17 | Clue: [t][i]m[e]s 18 | tiger 19 | Clue: [t][i][g][e][r] 20 | ''' 21 | 22 | 23 | def lingo(x): 24 | n = raw_input('Please input your five letter guess!\n') 25 | 26 | while n != x: 27 | output ='' 28 | for index, i in enumerate(n): 29 | if i in x: 30 | if n[index]==x[index]: 31 | output += '[' + i + ']' 32 | else: 33 | output += '(' + i + ')' 34 | else: 35 | output += i 36 | print 'Clue:' + output 37 | n = raw_input('Please input your five letter guess!\n') 38 | print 'Success' 39 | 40 | lingo('snake') 41 | 42 | -------------------------------------------------------------------------------- /42.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A sentence splitter is a program capable of splitting a text into sentences. 3 | The standard set of heuristics for sentence splitting includes (but isn't limited to) the following rules: 4 | Sentence boundaries occur at one of "." (periods), "?" or "!", except that 5 | 1. Periods followed by whitespace followed by a lower case letter are not sentence boundaries. 6 | 2. Periods followed by a digit with no intervening whitespace are not sentence boundaries. 7 | 3. Periods followed by whitespace and then an upper case letter, but preceded by any of a short list of titles are not sentence boundaries. 8 | Sample titles include Mr., Mrs., Dr., and so on. 9 | 4 Periods internal to a sequence of letters with no adjacent whitespace are not sentence boundaries 10 | (for example, www.aptex.com, or e.g). 11 | 5. Periods followed by certain kinds of punctuation (notably comma and more periods) are probably not sentence boundaries. 12 | 13 | Your task here is to write a program that given the name of a text file is able to write its content with each sentence on a separate line. 14 | Test your program with the following short text: 15 | 16 | Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? 17 | Adam Jones Jr. thinks he didn't. In any case, this isn't true... Well, with a probability of .9 it isn't. 18 | 19 | The result should be: 20 | 21 | Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. 22 | Did he mind? 23 | Adam Jones Jr. thinks he didn't. 24 | In any case, this isn't true... 25 | Well, with a probability of .9 it isn't. 26 | ''' 27 | 28 | import re 29 | 30 | text = "Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. \ 31 | Did he mind? Adam Jones Jr. thinks he didn't. In any case, \ 32 | this isn't true... Well, with a probability of .9 it isn't." 33 | 34 | # Method 1 35 | for i in re.findall(r'[A-Z][a-z]+\.?.*?[.?!](?= [A-Z]|$)', text): 36 | print i 37 | 38 | print '*'*80 39 | 40 | #Method 2 - using verbose mode. 41 | for i in re.findall(r''' 42 | [A-Z][a-z]+\.? # Starts with Capital includes (Mr., Mrs.) 43 | .*? # followed by anything 44 | [.?!] # ends with a (.)(?)(!) 45 | (?=\s[A-Z]|$) # is followed by whitespace and a capital letter 46 | ''', text, re.X): 47 | print i 48 | 49 | print '*'*80 50 | 51 | #Method 3 52 | for i in re.split(r'(?<=[^Mr|Mrs|Dr][.?!])\s(?=[A-Z])', text): 53 | print i 54 | 55 | 56 | -------------------------------------------------------------------------------- /43.py: -------------------------------------------------------------------------------- 1 | ''' 2 | An anagram is a type of word play, the result of rearranging 3 | the letters of a word or phrase to produce a new word or phrase, 4 | using all the original letters exactly once; e.g., orchestra = carthorse. 5 | Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, 6 | write a program that finds the sets of words that share the same characters 7 | that contain the most words in them. 8 | ''' 9 | 10 | import urllib 11 | import time 12 | 13 | 14 | def anagram(): 15 | start = time.clock() 16 | 17 | f = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt') 18 | words = set(f.read().split('\n')) 19 | d = { ''.join(sorted(i)):[] for i in words} 20 | 21 | for i in words: 22 | d[''.join(sorted(i))].append(i) 23 | max_len = max( len(v) for v in d.values()) 24 | 25 | for v in d.values(): 26 | if len(v)==max_len: 27 | print v 28 | 29 | end = time.clock() 30 | print end - start 31 | 32 | 33 | anagram() -------------------------------------------------------------------------------- /44.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Your task in this exercise is as follows: 3 | 4 | Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order. 5 | Determine whether the generated string is balanced; that is, whether it consists entirely of pairs 6 | of opening/closing brackets (in that order), none of which mis-nest. 7 | Examples: 8 | 9 | [] OK ][ NOT OK 10 | [][] OK ][][ NOT OK 11 | [[][]] OK []][[] NOT OK 12 | ''' 13 | 14 | import random 15 | 16 | def find_balanced(n): 17 | count_left, count_right = 0,0 18 | s = [random.choice(['[',']']) for i in range(int(n))] 19 | for i in s: 20 | if count_left == count_right: 21 | if i ==']': 22 | return ''.join(s) + ' not balanced' 23 | if i =='[': 24 | count_left +=1 25 | else: 26 | count_right +=1 27 | if count_left == count_right: 28 | return ''.join(s) + ' balanced' 29 | else: 30 | return ''.join(s) + ' not balanced' 31 | 32 | for i in range(20): 33 | print find_balanced(50) 34 | 35 | -------------------------------------------------------------------------------- /45.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A certain childrens game involves starting with a word in a particular category. Each participant in 3 | turn says a word, but that word must begin with the final letter of the previous word. 4 | Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, 5 | they fall out of the game. For example, with "animals" as the category, 6 | 7 | Child 1: dog 8 | Child 2: goldfish 9 | Child 1: hippopotamus 10 | Child 2: snake 11 | 12 | Your task in this exercise is as follows: Take the following selection of 70 English Pokemon names 13 | (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible 14 | number of Pokemon names where the subsequent name starts with the final letter of the preceding name. 15 | No Pokemon name is to be repeated. 16 | 17 | audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon 18 | cresselia croagunk darmanitan deino emboar emolga exeggcute gabite 19 | girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan 20 | kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine 21 | nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 22 | porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking 23 | sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko 24 | tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask 25 | ''' 26 | 27 | 28 | 29 | 30 | from collections import defaultdict 31 | import time 32 | 33 | pokemon = '''audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon 34 | cresselia croagunk darmanitan deino emboar emolga exeggcute gabite 35 | girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan 36 | kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine 37 | nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 38 | porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking 39 | sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko 40 | tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask'''.split() 41 | 42 | 43 | # Method 1 44 | def find(chain): 45 | last_character = chain[-1][-1] 46 | options = d[last_character] - set(chain) 47 | 48 | if not options: 49 | return chain 50 | else: 51 | return max( (find(chain+[i]) for i in options), key=len) 52 | 53 | 54 | start = time.clock() 55 | 56 | d = defaultdict(set) 57 | for word in pokemon: 58 | d[word[0]].add(word) 59 | 60 | print max( (find([word]) for word in pokemon), key=len) 61 | 62 | end = time.clock() 63 | print end - start 64 | 65 | 66 | 67 | # Method 2 try bottom down approach 68 | def find2(chain): 69 | first_character = chain[0][0] 70 | options = d[first_character] -set(chain) 71 | 72 | if not options: 73 | return chain 74 | else: 75 | return max( (find2([i]+ chain) for i in options), key=len) 76 | 77 | start = time.clock() 78 | d = defaultdict(set) 79 | for word in pokemon: 80 | d[word[-1]].add(word) 81 | 82 | print max( (find2([word]) for word in pokemon), key=len) 83 | end = time.clock() 84 | print end - start 85 | 86 | 87 | 88 | # Method 3 - Using loop instead of generator expression 89 | def find(chain): 90 | l=[] 91 | last_character = chain[-1][-1] 92 | options = d[last_character] - set(chain) 93 | 94 | if not options: 95 | return chain 96 | else: 97 | for i in options: 98 | l.append(find(chain+[i])) 99 | return max(l, key=len) 100 | 101 | #return [ find(chain+[i]) f=or i in options] 102 | 103 | pokemon = set(pokemon) 104 | 105 | d = defaultdict(set) 106 | for word in pokemon: 107 | d[word[0]].add(word) 108 | 109 | print max( [find([word]) for word in pokemon], key=len) 110 | 111 | 112 | 113 | 114 | 115 | # Just try it out to have a better understanding how return plays an important role in recursion 116 | 117 | def find(chain): 118 | last_character = chain[-1][-1] 119 | options = d[last_character] - set(chain) 120 | 121 | if not options: 122 | return chain 123 | else: 124 | for i in options: 125 | find(chain+[i]) 126 | #to understand importance of return, here once we are in else block nothing is returned 127 | 128 | 129 | pokemon = set(pokemon) 130 | 131 | d = defaultdict(set) 132 | for word in pokemon: 133 | d[word[0]].add(word) 134 | 135 | print [find([word]) for word in pokemon] 136 | 137 | 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /46.py: -------------------------------------------------------------------------------- 1 | ''' 2 | An alternate is a word in which its letters, taken alternatively in a strict 3 | sequence, and used in the same order as the original word, 4 | make up at least two other words. All letters must be used, 5 | but the smaller words are not necessarily of the same length. 6 | For example, a word with seven letters where every second letter 7 | is used will produce a four-letter word and a three-letter word. 8 | Here are two examples: 9 | "board": makes "bad" and "or". 10 | "waists": makes "wit" and "ass". 11 | Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, 12 | write a program that goes through each word in the list 13 | and tries to make two smaller words using every second letter. 14 | The smaller words must also be members of the list. 15 | Print the words to the screen in the above fashion. 16 | ''' 17 | 18 | 19 | import urllib2 20 | import time 21 | 22 | data = urllib2.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read() 23 | words_list = set(data.split('\n')) #Try chaging set to list "list(data.split('\n'))" and notice the difference in timings. 24 | 25 | start = time.clock() 26 | for line in words_list: 27 | total =[] 28 | alternate, alternate2 = '','' 29 | for i in range(0,len(line),2): 30 | alternate = alternate + line[i] 31 | if alternate in words_list and len(alternate)>2: 32 | total.append(alternate) 33 | for i in range(1,len(line),2): 34 | alternate2 = alternate + line[i] 35 | if alternate2 in words_list and len(alternate2)>2: 36 | total.append(alternate2) 37 | if len(total)==2: 38 | print "%s: makes %s and %s" %(line,alternate, alternate2) 39 | end = time.clock() 40 | print end-start -------------------------------------------------------------------------------- /47. Code Jam.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Below links have the Google Code Jam qualification round practice problems. 3 | 1. https://code.google.com/codejam/contest/351101/dashboard#s=p0 4 | 2. https://code.google.com/codejam/contest/351101/dashboard#s=p1 5 | ''' 6 | 7 | #1st Problem - Store Credit 8 | def solve(path,out): 9 | f = open(path, 'r') 10 | o = open(out, 'w') 11 | 12 | test_cases = int(f.readline()) 13 | 14 | for c in range(test_cases): 15 | credit = int(f.readline()) 16 | items = int(f.readline()) 17 | nos = map(int, f.readline().rstrip().split(' ')) 18 | 19 | for i in range(items): 20 | for j in range(i+1, items): 21 | if nos[i] + nos[j] ==credit: 22 | o.write('Case #{}: {} {}\n'.format(c+1, i+1, j+1)) 23 | break 24 | f.close() 25 | o.close() 26 | 27 | # Replace with your file input and output paths 28 | solve('C:\Users\my\Desktop\A-Large-practice.in', 29 | 'C:\Users\my\Desktop\A-Large-practice.out') 30 | 31 | 32 | 33 | 34 | # 2nd Problem - Reverse words 35 | def solve(path,out): 36 | f = open(path, 'r') 37 | o = open(out, 'w') 38 | 39 | test_cases = int(f.readline()) 40 | 41 | for c in range(test_cases): 42 | line = f.readline().split() 43 | print line 44 | print 'Case #{}: {}\n'.format(c+1, ' '.join(line[::-1])) 45 | o.write('Case #{}: {}\n'.format(c+1, ' '.join(line[::-1]))) 46 | 47 | #replace with your file input and output paths 48 | solve('C:\Users\my\Desktop\B-large-practice.in', 49 | 'C:\Users\my\Desktop\B-large-practice.out') 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /48. Gmail Bomb.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Make a Python script that sends an email to a Gmail User. 3 | Finally convert it to a bomb. 4 | The script will qualify as a bomb if it is able to send 50 emails to the user. 5 | ''' 6 | 7 | import smtplib 8 | 9 | def send_email(): 10 | # Enter your login credentials below 11 | username = 'sendanonymous90' 12 | password = '*******' 13 | FROM = 'sendanonymous90@gmail.com' 14 | TO = 'receivetestmail@gmail.com ' 15 | SUBJECT = 'TEST' 16 | TEXT = 'Hi there, you have received a lottery of 1000$.' 17 | 18 | message = """From: %s\nTo: %s\nSubject: %s\n\n%s""" %(FROM, TO, SUBJECT, TEXT) 19 | 20 | server = smtplib.SMTP("smtp.gmail.com", 587) 21 | server.starttls() 22 | server.login(username, password) 23 | 24 | count =0 25 | for i in range(500): 26 | server.sendmail(FROM, TO, message) 27 | print 'Success' 28 | count +=1 29 | print count 30 | 31 | server.close() 32 | 33 | 34 | send_email() 35 | 36 | -------------------------------------------------------------------------------- /49. Fb_bomb.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Make a Python script which adds comments to your any of the post on your timeline. 3 | The script will qualify as a bomb if it is able to comment 50 times on a single post. 4 | ''' 5 | 6 | import requests 7 | import json 8 | 9 | #replace with your access token, to be found at https://developers.facebook.com/tools/explorer 10 | accesstoken = 'CAACEdEose0cBAEP7zZCdStYw0TYVpnviOFbZB6XuZAEZCdbZBWjAqZAE2s8QVJW646QZB7u3nAxipKIjKhtZAmsmRSUAZCSV731ZAhrIBvTKxpFRsW4yUoSt1R7TnUnmcb83TYBcY2u3KDbSVZB2gtBdZBQ0E4zPw22vAk1ms9gjwvl3yIjCTYQ4tuh30WARyuhBXiSJH20CbrZBUUwZDZD' 11 | 12 | query = 'SELECT post_id , created_time FROM stream where source_id = me()' 13 | d = { 'access_token': accesstoken, 'q':query} 14 | 15 | base_url = 'https://graph.facebook.com' 16 | r = requests.get(base_url + "/fql", params=d) 17 | result = json.loads(r.text) 18 | posts = result['data'] 19 | post1 = posts[0] 20 | 21 | comments_url = base_url + '/{}/comments'.format(post1['post_id']) 22 | 23 | count =1 24 | for i in range(50): 25 | msg = {'access_token': accesstoken, 'message': 'Bomb' + str(count)} 26 | requests.post(comments_url, data = msg) 27 | count+=1 28 | print count 29 | 30 | -------------------------------------------------------------------------------- /50. Youtube_downloader.py: -------------------------------------------------------------------------------- 1 | '''Make a Python script which downloads the You tube video. The video should be saved for future use.''' 2 | 3 | 4 | from urllib2 import urlopen 5 | from urlparse import unquote 6 | import re 7 | 8 | url ='https://www.youtube.com/watch?v=Wt1wFf53e2o' 9 | response = urlopen(url) 10 | content = response.read() 11 | direct_urls = re.findall(r'"url_encoded_fmt_stream_map":.*?url=(https.*?)(,|\\u0026)', content) 12 | 13 | direct_url = unquote(direct_urls[0][0]) 14 | 15 | d = urlopen(direct_url) 16 | f = open('Test_video.avi', 'wb') 17 | 18 | #This will save the video to your default path. To change path use os.chdir(path) 19 | #Also note this will read the whole file into the memory and than write. We did this to make it words shortest script. 20 | #Instead read a chunk and write till complete. 21 | f.write(d.read()) 22 | 23 | d.close() 24 | f.close() 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 garg10may 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-for-Beginners-Solve-50-Exercises-Live 2 | 3 | ##### Very Simple Exercises 4 | 5 | 1. Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python. (It is true that Python has the max() function built in, but writing it yourself is nevertheless a good exercise.) 6 | 7 | 2. Define a function max_of_three() that takes three numbers as arguments and returns the largest of them. 8 | 9 | 3. Define a function that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.) 10 | 11 | 4. Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise. 12 | 13 | 5. Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon". 14 | 15 | 6. Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24. 16 | 17 | 7. Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I". 18 | 19 | 8. Define a function is_palindrome() that recognizes palindromes (i.e. words that look the same written backwards). For example, is_palindrome("radar") should return True. 20 | 21 | 9. Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.) 22 | 23 | 10. Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops. 24 | 25 | 11. Define a function generate_n_chars() that takes an integer n and a character c and returns a string, n characters long, consisting only of c:s. For example, generate_n_chars(5,"x") should return the string "xxxxx". (Python is unusual in that you can actually write an expression 5 * "x" that will evaluate to "xxxxx". For the sake of the exercise you should ignore that the problem can be solved in this manner.) 26 | 27 | 12. Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. For example, histogram([4, 9, 7]) should print the following: 28 | 29 | ``` 30 | **** 31 | ********* 32 | ******* 33 | ``` 34 | 35 | 13. The function max() from exercise 1) and the function max_of_three() from exercise 2) will only work for two and three numbers, respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list of numbers and returns the largest one. 36 | 37 | 14. Write a program that maps a list of words into a list of integers representing the lengths of the correponding words. 38 | 39 | 15. Write a function find_longest_word() that takes a list of words and returns the length of the longest one. 40 | 41 | 16. Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n. 42 | 43 | 17. Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", "Rise to vote sir", or the exclamation "Dammit, I'm mad!". Note that punctuation, capitalization, and spacing are usually ignored. 44 | 45 | 18. A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence to see if it is a pangram or not. 46 | 47 | 19. "99 Bottles of Beer" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows: 48 | 49 | 99 bottles of beer on the wall, 99 bottles of beer. 50 | Take one down, pass it around, 98 bottles of beer on the wall. 51 | 52 | The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero. 53 | Your task here is write a Python program capable of generating all the verses of the song. 54 | 55 | 20. Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"} and use it to translate your Christmas cards from English into Swedish. That is, write a function translate() that takes a list of English words and returns a list of Swedish words. 56 | 57 | 21. Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab"). 58 | 59 | 22. In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary: 60 | ``` 61 | key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 62 | 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 63 | 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 64 | 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 65 | 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 66 | 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 67 | 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'} 68 | ``` 69 | 70 | Your task in this exercise is to implement an encoder/decoder of ROT-13. Once you're done, you will be able to read the following secret message: 71 | 72 | `Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!` 73 | 74 | Note that since English has 26 characters, your ROT-13 program will be able to both encode and decode texts written in English. 75 | 76 | 23. Define a simple "spelling correction" function correct() that takes a string and sees to it that 1) two or more occurrences of the space character is compressed into one, and 2) inserts an extra space after a period if the period is directly followed by a letter. E.g. correct("This is very funny and cool.Indeed!") should return "This is very funny and cool. Indeed!" Tip: Use regular expressions! 77 | 78 | 24. The third person singular verb form in English is distinguished by the suffix -s, which is added to the stem of the infinitive form: run -> runs. A simple set of rules can be given as follows: 79 | 80 | - If the verb ends in y, remove it and add ies 81 | - If the verb ends in o, ch, s, sh, x or z, add es 82 | - By default just add s 83 | 84 | Your task in this exercise is to define a function make_3sg_form() which given a verb in infinitive form returns its third person singular form. Test your function with words like try, brush, run and fix. Note however that the rules must be regarded as heuristic, in the sense that you must not expect them to work for all cases. Tip: Check out the string method endswith(). 85 | 86 | 25. In English, the present participle is formed by adding the suffix -ing to the infinite form: go -> going. A simple set of heuristic rules can be given as follows: 87 | 88 | - If the verb ends in e, drop the e and add ing (if not exception: be, see, flee, knee, etc.) 89 | - If the verb ends in ie, change ie to y and add ing 90 | - For words consisting of consonant-vowel-consonant, double the final letter before adding ing 91 | - By default just add ing 92 | 93 | Your task in this exercise is to define a function make_ing_form() which given a verb in infinitive form returns its present participle form. Test your function with words such as lie, see, move and hug. However, you must not expect such simple rules to work for all cases. 94 | 95 | ##### Higher order functions and list comprehensions 96 | 97 | 26. Using the higher order function reduce(), write a function max_in_list() that takes a list of numbers and returns the largest one. Then ask yourself: why define and call a new function, when I can just as well call the reduce() function directly? 98 | 99 | 27. Write a program that maps a list of words into a list of integers representing the lengths of the correponding words. Write it in three different ways: 1) using a for-loop, 2) using the higher order function map(), and 3) using list comprehensions. 100 | 101 | 28. Write a function find_longest_word() that takes a list of words and returns the length of the longest one. Use only higher order functions. 102 | 103 | 29. Using the higher order function filter(), define a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n. 104 | 105 | 30. Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"} and use it to translate your Christmas cards from English into Swedish. Use the higher order function map() to write a function translate() that takes a list of English words and returns a list of Swedish words. 106 | 107 | 31. Implement the higher order functions map(), filter() and reduce(). (They are built-in but writing them yourself may be a good exercise.) 108 | 109 | ##### Simple exercises including I/O 110 | 111 | 32. Write a version of a palindrome recogniser that accepts a file name from the user, reads each line, and prints the line to the screen if it is a palindrome. 112 | 113 | 33. According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. ("Semordnilap" is itself "palindromes" spelled backwards.) Write a semordnilap recogniser that accepts a file name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilaps to the screen. For example, if "stressed" and "desserts" is part of the word list, the the output should include the pair "stressed desserts". Note, by the way, that each pair by itself forms a palindrome! 114 | 115 | 34. Write a procedure char_freq_table() that, when run in a terminal, accepts a file name from the user, builds a frequency listing of the characters contained in the file, and prints a sorted and nicely formatted character frequency table to the screen. 116 | 117 | 35. 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 one version of the ICAO alphabet: 118 | ``` 119 | d = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot', 120 | 'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima', 121 | 'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo', 122 | 's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey', 123 | 'x':'x-ray', 'y':'yankee', 'z':'zulu'} 124 | ``` 125 | Your task in this exercise is to write a procedure speak_ICAO() able to translate any text (i.e. any string) into spoken ICAO words. You need to import at least two libraries: os and time. On a mac, you have access to the system TTS (Text-To-Speech) as follows: os.system('say ' + msg), where msg is the string to be spoken. (Under UNIX/Linux and Windows, something similar might exist.) Apart from the text to be spoken, your procedure also needs to accept two additional parameters: a float indicating the length of the pause between each spoken ICAO word, and a float indicating the length of the pause between each word spoken. 126 | 127 | 36. A hapax legomenon (often abbreviated to hapax) is a word which occurs only once in either the written record of a language, the works of an author, or in a single text. Define a function that given the file name of a text will return all its hapaxes. Make sure your program ignores capitalization. 128 | 129 | 37. Write a program that given a text file will create a new text file in which all the lines from the original file are numbered from 1 to n (where n is the number of lines in the file). 130 | 131 | 38. Write a program that will calculate the average word length of a text stored in a file (i.e the sum of all the lengths of the word tokens in the text, divided by the number of word tokens). 132 | 133 | 39. Write a program able to play the "Guess the number"-game, where the number to be guessed is randomly chosen between 1 and 20. (Source: http://inventwithpython.com) This is how it should work when run in a terminal: 134 | ``` 135 | Hello! What is your name? 136 | Torbjörn 137 | Well, Torbjörn, I am thinking of a number between 1 and 20. 138 | Take a guess. 139 | 10 140 | Your guess is too low. 141 | Take a guess. 142 | 15 143 | Your guess is too low. 144 | Take a guess. 145 | 18 146 | Good job, Torbjörn! You guessed my number in 3 guesses! 147 | ``` 148 | 149 | 40. An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; e.g., orchestra = carthorse, A decimal point = I'm a dot in place. Write a Python program that, when started 1) randomly picks a word w from given list of words, 2) randomly permutes w (thus creating an anagram of w), 3) presents the anagram to the user, and 4) enters an interactive loop in which the user is invited to guess the original word. It may be a good idea to work with (say) colour words only. The interaction with the program may look like so: 150 | 151 | ``` 152 | Colour word anagram: onwbr 153 | Guess the colour word! 154 | black 155 | Guess the colour word! 156 | brown 157 | Correct! 158 | ``` 159 | 160 | 41. In a game of Lingo, there is a hidden word, five characters long. The object of the game is to find this word by guessing, and in return receive two kinds of clues: 1) the characters that are fully correct, with respect to identity as well as to position, and 2) the characters that are indeed present in the word, but which are placed in the wrong position. Write a program with which one can play Lingo. Use square brackets to mark characters correct in the sense of 1), and ordinary parentheses to mark characters correct in the sense of 2). Assuming, for example, that the program conceals the word "tiger", you should be able to interact with it in the following way: 161 | 162 | ``` 163 | snake 164 | Clue: snak(e) 165 | fiest 166 | Clue: f[i](e)s(t) 167 | times 168 | Clue: [t][i]m[e]s 169 | tiger 170 | Clue: [t][i][g][e][r] 171 | ``` 172 | 173 | ##### Somewhat harder exercises 174 | 175 | 42. A sentence splitter is a program capable of splitting a text into sentences. The standard set of heuristics for sentence splitting includes (but isn't limited to) the following rules: 176 | 177 | - Sentence boundaries occur at one of "." (periods), "?" or "!", except that 178 | - Periods followed by whitespace followed by a lower case letter are not sentence boundaries. 179 | - Periods followed by a digit with no intervening whitespace are not sentence boundaries. 180 | - Periods followed by whitespace and then an upper case letter, but preceded by any of a short list of titles are not sentence boundaries. Sample titles include Mr., Mrs., Dr., and so on. 181 | - Periods internal to a sequence of letters with no adjacent whitespace are not sentence boundaries (for example, www.aptex.com, or e.g). 182 | - Periods followed by certain kinds of punctuation (notably comma and more periods) are probably not sentence boundaries. 183 | 184 | Your task here is to write a program that given the name of a text file is able to write its content with each sentence on a separate line. Test your program with the following short text: Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn't. In any case, this isn't true... Well, with a probability of .9 it isn't. The result should be: 185 | 186 | Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. 187 | Did he mind? 188 | Adam Jones Jr. thinks he didn't. 189 | In any case, this isn't true... 190 | Well, with a probability of .9 it isn't. 191 | 192 | 43. An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; e.g., orchestra = carthorse. Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, write a program that finds the sets of words that share the same characters that contain the most words in them. 193 | 194 | 44. Your task in this exercise is as follows: 195 | 196 | Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order. 197 | Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. 198 | Examples: 199 | ``` 200 | [] OK ][ NOT OK 201 | [][] OK ][][ NOT OK 202 | [[][]] OK []][[] NOT OK 203 | ``` 204 | 205 | 45. A certain childrens game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. For example, with "animals" as the category, 206 | ``` 207 | Child 1: dog 208 | Child 2: goldfish 209 | Child 1: hippopotamus 210 | Child 2: snake 211 | ``` 212 | Your task in this exercise is as follows: Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated. 213 | 214 | >audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon 215 | >cresselia croagunk darmanitan deino emboar emolga exeggcute gabite 216 | >girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan 217 | >kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine 218 | >nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 219 | >porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking 220 | >sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko 221 | >tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask 222 | 223 | 46. An alternate is a word in which its letters, taken alternatively in a strict sequence, and used in the same order as the original word, make up at least two other words. All letters must be used, but the smaller words are not necessarily of the same length. For example, a word with seven letters where every second letter is used will produce a four-letter word and a three-letter word. Here are two examples: 224 | 225 | - "board": makes "bad" and "or". 226 | - "waists": makes "wit" and "ass". 227 | 228 | Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, write a program that goes through each word in the list and tries to make two smaller words using every second letter. The smaller words must also be members of the list. Print the words to the screen in the above fashion. 229 | 230 | 231 | ##### Fun Exercises 232 | 233 | 47. Google Code Jam 234 | 235 | - https://code.google.com/codejam/contest/351101/dashboard#s=p0 236 | - https://code.google.com/codejam/contest/351101/dashboard#s=p1 237 | 238 | 48. Make a Python script that sends an email to a Gmail User. Finally convert it to a bomb. The script will qualify as a bomb if it is able to send 50 emails to the user. 239 | 240 | 49. Make a Python script which adds comments to your any of the post on your timeline. The script will qualify as a bomb if it is able to comment 50 times on a single post. 241 | 242 | 50. Make a Python script which downloads the You tube video. The video should be saved for future use. 243 | -------------------------------------------------------------------------------- /numbered_sample_text.txt: -------------------------------------------------------------------------------- 1 | 1. apple 2 | 2. bananna 3 | 3. car 4 | 4. mango 5 | 5. python 6 | -------------------------------------------------------------------------------- /sample text.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum nec felis nulla, non volutpat tellus. Cras dolor libero, fringilla ac eleifend non, congue a lacus. Etiam interdum dictum eleifend. Phasellus ut semper eros. Phasellus egestas lacus et turpis euismod cursus at non erat. Donec eu posuere lectus. Phasellus ametus quis metus sollicitudin malesuada a at nulla. Maecenas rhoncus hendrerit lectus quis faucibus. Phasellus imperdiet consequat lacus, condimentum fringilla justo malesuada et.Mauris in faucibus dui. Duis venenatis leo vel arcu congue eu luctus dui pharetra. Praesent porta semper nisi nec elementum. Sed eget nunc vitae risus ultricies dignissim consequat ac nulla. Curabitur vestibulum vulputate est. Nunc dolor elit, tempor quis nunc. Etiam eget turpis augue. Cum sociis natoque penatibus et magnis nulla. Proin a mauris dui. Suspendisse potenti. Duis in arcu sed est ornare lacinia ac ac felis.Donec porttitor blandit accumsan. Fusce mattis sagittis viverra. Ut vestibulum dapibus leo in porttitor. Praesent consectetur, arcu vel aliquet aliquet, nulla felis dignissim justo, non consequat dolor arcu eget dui. Sed scelerisque tortor at massa fermentum interdum. Maecenas convallis ante sit amet odio vehicula id malesuada quam convallis. Sed ac ipsum lectus. Nam nec libero sed dui ultrices auctor congue luctus mi. Nunc placerat ante vulputate mi lobortis vel blandit dolor pharetra. Sed augue augue, mollis vitae cursus at, rhoncus et sem. Nulla elit ligula, gravida in vulputate a, scelerisque quis tortor. Integer tristique gravida nulla, sit amet facilisis eros dictum id.Nulla tortor nisi, condimentum non cursus sit amet, malesuada in libero. Quisque tincidunt eros et est auctor dictum eget non dolor. Nulla velit sem, aliquam eu tincidunt et, hendrerit vitae lorem. Vestibulum ultricies gravida tristique. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam magna odio, bibendum quis gravida in, mollis ac leo. Cras id ipsum enim. Pellentesque fringilla euismod metus, nec laoreet dui auctor ac. Nulla neque lacus, euismod id pellentesque Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum nec felis nulla, non volutpat tellus. Cras dolor libero, fringilla ac eleifend non, congue a lacus. Etiam interdum dictum eleifend. Phasellus ut semper eros. Phasellus egestas lacus et turpis euismod cursus at non erat. Donec eu posuere lectus. Phasellus a metus quis metus sollicitudin malesuada a at nulla. Maecenas rhoncus hendrerit lectus quis faucibus. Phasellus imperdiet consequat lacus, condimentum fringilla justo malesuada et. Mauris in faucibus dui. Duis venenatis leo vel arcu congue eu luctus dui pharetra. Praesent porta semper nisi nec elementum. Sed eget nunc vitae risus ultricies dignissim consequat ac nulla. Curabitur vestibulum vulputate est. Nunc dolor elit, tempor quis pretium vitae, venenatis venenatis odio. Sed quis turpis nibh, vel rhoncus felis. Suspendisse vel ante nulla, sit amet facilisis tortor. Suspendisse potenti. Integer libero lectus, hendrerit at dapibus sed, porta vitae sem. In a mi placerat lectus euismod sollicitudin. Quisque eu felis sed diam consequat cursus sit amet a tellus. Donec eros lectus, sollicitudin id tincidunt luctus, mattis vitae purus. Mauris ut tellus turpis. Sed eget elit velit.Phasellus molestie nunc sed sapien malesuada commodo. Vestibulum laoreet molestie ipsum a interdum. Maecenas a lorem pharetra risus mattis tincidunt ac a nulla. Proin a mauris dui. Suspendisse potenti. Duis in arcu sed est ornare lacinia ac ac felis. Donec porttitor blandit accumsan. Fusce mattis sagittis viverra. Ut vestibulum dapibus leo in porttitor. Praesent consectetur, arcu vel aliquet aliquet, nulla felis dignissim justo, non consequat dolor arcu eget dui. Sed scelerisque tortor at massa fermentum interdum. Maecenas convallis ante sit amet odio vehicula id malesuada quam convallis. Sed ac ipsum lectus. Nam nec libero sed dui ultrices auctor congue luctus mi. Nunc placerat ante vulputate mi lobortis vel blandit dolor pharetra. Sed augue augue, mollis vitae cursus at, rhoncus et sem. Nulla elit ligula, gravida in vulputate a, scelerisque quis tortor. Integer tristique gravida nulla, sit amet facilisis eros dictum id.Nulla tortor nisi, condimentum non cursus sit amet, malesuada in libero. Quisque tincidunt eros et est auctor dictum eget non dolor. Nulla velit sem, aliquam eu tincidunt et, hendrerit vitae lorem. Vestibulum ultricies gravida tristique. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam magna odio, bibendum quis gravida in, mollis ac leo. Cras id ipsum enim. Pellentesque fringilla euismod metus, nec laoreet dui auctor ac. Nulla neque lacus, euismod id pellentesque quis, gravida ac orci. In at tortor nunc. Etiam eget turpis augue. Cum sociis natoque penatibus et magnis nulla. Proin a mauris dui. Suspendisse potenti. Duis in arcu sed est ornare lacinia ac ac felis. Donec porttitor blandit accumsan. Fusce mattis sagittis viverra. Ut vestibulum dapibus leo in porttitor. Praesent consectetur, arcu vel aliquet aliquet, nulla felis dignissim justo, non consequat dolor arcu nulla. Proin a mauris dui. Suspendisse potenti. Duis in arcu sed est ornare lacinia ac ac felis. Donec porttitor blandit accumsan. Fusce mattis sagittis viverra. Ut vestibulum dapibus leo in porttitor. Praesent consectetur, arcu vel aliquet aliquet, nulla felis dignissim justo, non consequat dolor arcu eget dui. Sed scelerisque tortor at massa fermentum interdum. Maecenas convallis ante sit amet odio vehicula id malesuada quam convallis. Sed ac ipsum lectus. Nam nec libero sed dui ultrices auctor congue luctus mi. Nunc placerat ante vulputate mi lobortis vel blandit dolor pharetra. Sed augue augue, mollis vitae cursus at, rhoncus et sem. Nulla elit ligula, gravida in vulputate a, scelerisque quis tortor. Integer tristique gravida nulla, sit amet facilisis eros dictum id.Nulla tortor nisi, condimentum non cursus sit amet, malesuada in libero. Quisque tincidunt eros et est auctor dictum eget non dolor. Nulla velit sem, aliquam eu tincidunt et, hendrerit vitae lorem. Vestibulum ultricies gravida tristique. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam magna odio, bibendum quis gravida in, mollis ac leo. Cras id ipsum enim. Pellentesque fringilla euismod metus, nec laoreet dui auctor ac. Nulla neque lacus, euismod id pellentesque quis, gravida ac orci. In at tortor nunc. Etiam eget turpis augue. Cum sociis natoque penatibus et magnis nulla. Proin a mauris dui. Suspendisse potenti. Duis in arcu sed est ornare lacinia ac ac felis. Donec porttitor blandit accumsan. Fusce mattis sagittis viverra. Ut vestibulum dapibus leo in porttitor. Praesent consectetur, arcu vel aliquet aliquet, nulla felis dignissim justo, non consequat dolor arcu nulla. Proin a mauris dui. Suspendisse potenti. Duis in arcu sed est ornare lacinia ac ac felis. Donec porttitor blandit accumsan. Fusce mattis sagittis viverra. Ut vestibulum dapibus leo in porttitor. Praesent consectetur, arcu vel aliquet aliquet, nulla felis dignissim justo, non consequat dolor arcu eget dui. Sed scelerisque tortor at massa fermentum interdum. Maecenas convallis ante sit amet odio vehicula id malesuada quam convallis. Sed ac ipsum lectus. Nam nec libero sed dui ultrices auctor congue luctus mi. Nunc placerat ante vulputate mi lobortis vel blandit dolor pharetra. Sed augue augue, mollis vitae cursus at, rhoncus et sem. Nulla elit ligula, gravida in vulputate a, scelerisque quis tortor. Integer tristique gravida nulla, sit amet facilisis eros dictum id.Nulla tortor nisi, condimentum non cursus sit amet, malesuada in libero. Quisque tincidunt eros et est auctor dictum eget non dolor. Nulla velit sem, aliquam eu tincidunt et, hendrerit vitae lorem. Vestibulum ultricies gravida tristique. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam magna odio, bibendum quis gravida in, mollis ac leo. Cras id ipsum enim. Pellentesque fringilla euismod metus, nec laoreet dui auctor ac. Nulla neque lacus, euismod id pellentesque quis, gravida ac orci. In at tortor nunc. Etiam eget turpis augue. Cum sociis natoque penatibus et magnis nulla. Proin a mauris dui. Suspendisse potenti. Duis in arcu sed est ornare lacinia ac ac felis. Donec porttitor blandit accumsan. Fusce mattis sagittis viverra. Ut vestibulum dapibus leo in porttitor. Praesent consectetur, arcu vel aliquet aliquet, nulla felis -------------------------------------------------------------------------------- /sample_text.txt: -------------------------------------------------------------------------------- 1 | apple 2 | bananna 3 | car 4 | mango 5 | python 6 | --------------------------------------------------------------------------------