Small Exercises for Programming Skills

Small Exercises for Programming Skills
Slide Note
Embed
Share

Practice makes perfect! Engage in a series of small exercises to enhance your programming skills. From defining functions to writing interactive programs, these exercises cover various concepts in a hands-on manner. Sharpen your coding abilities with these engaging tasks.

  • Programming
  • Practice
  • Functions
  • Exercises
  • Python

Uploaded on Mar 09, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Loops

  2. Loops

  3. Practice makes perfect. A bunch of small exercises. Goes entirely to the exercise session of Friday. 3

  4. Ex. 33, Ex. 35 (with cut/paste on prints) Ex. 38 (skip long introduction)

  5. The assignments The model solutions Explanation on methodology (why)

  6. Exercise 1: Define a function differences, that takes as an argument a list of integers and returns the list of differences between consecutive elements of the list. Example: differences([9,2,5,7,3]) returns [7, -3, -2, 4]. - for i in range(len(list)): calculate list[i] list[i+1] def differences(list): list2 = [] for i in range(len(list)- 1): print list2 return list2 list2.append(list[i] - list[i+1])

  7. Exercise 2: Define a function create_duplicates, taking an argument with a list of integers and returning a new list of integers, in which every integer of the input argument now occurs as often as its own value. Example: create_duplicates([3,2,4]) returns [3,3,3,2,2,4,4,4,4]. - for num in list: for i in range(num): def create_duplicates(list): list2 = [] for num in list: print list2 return list2 for i in range(num): list2.append(num)

  8. Exercise 3: Write a program that keeps on asking a user for a plural noun and a number. If the text string is stop , the program should not even ask for the number, but just stop. If not, the program should print to the screen: You asked me to print number noun . That is: number and noun . Your program should use text-concatenation for one of the print instructions, but should not use text-concatenation for the other print-instructions. - while noun != stop ? while True: text = raw_input("Give me a plural noun:") if text == "stop": break else: number = raw_input("Give me a number:") print 'You asked me to print "%s %s".' % (number, text) print 'That is: "' + number + '" and "' + text + '".'

  9. Exercise 4: Define a function sum_is_7_multiple, with one argument: list. The list is assumed to be a list of integer numbers. Your program should add up the different digits in each of the integers and check whether that sum is a multiple of 7. The program prints and returns the list of all input integers for which this sum is a multiple of 7. Example: sum_is_7_multiple([123, 43, 401, 77]) gives that [43,77] is printed to the screen and returns [43, 77]. - - One function: what is the sum of the digits of a number? Second function: is a number devisable by 7? def sum_is_7_multiple(list): list7 = [] for num in list: if sum_digits(num) % 7 == 0: list7.append(num) print list7 return list7 def sum_digits(num): text = str(num) sum = 0 for i in range(len(text)): sum = sum + int(text[i]) return sum

  10. Exercise 5: Define a function scramble_sort that takes as an argument a list of integers. Your function should print and return a new list, consisting of the maximum of the input list, then the minimum of the input list, then the second largest from the input list, then the second smallest, etc. Example: scramble_sort([5,9,2,5,1,6]) prints and returns [9,1,6,2,5,5], scramble_sort([4,8]) prints and returns [8,4]. You probably need a function that can remove the last selected number from the input list The for the top function: test while the list != [] scrambled = [] while list != []: if counter % 2 == 1: next = max(list) else: next = min(list) list = remove_one(list, next) scrambled.append(next) counter += 1 print scrambled return scrambled - def scramble_sort(list): counter = 1 - def remove_one(list, mem): new_list = [] removed = False for el in list: if el != mem or removed: new_list.append(el) else: removed = True return new_list

  11. Exercise 6: Define a function mult_decompose that takes 2 arguments: an integer number and a list of integer numbers. The function returns a directory. The keys of the directory are the numbers in the list in the second argument. The value associated to each key in the directory is the number of times that the first argument of mult-decompose is devisable by the key. Example: mult- decompose(120, [2,3,4,5,7]) returns { 2 : 3, 3 : 1, 4: 1, 5 : 1, 7 : 0}. def mult_decompose(number, list): dir = {} for num in list: - For an empty directory: run through the numbers in the list and create a key and value for it. The value is how often it divides the first number. number_new = number num_div = 0 still_divides = True while still_divides: if number_new % num == 0: num_div +=1 number_new = number_new / num else: still_divides = False dir[num] = num_div return dir

  12. def sort_types(list): type_dir = {} type_dir["words"] = [] type_dir["longer texts"] = [] type_dir["bools"] = [] type_dir["pos integers"] = [] type_dir["neg integers"] = [] type_dir["floats"] = [] for mem in list: if isinstance(mem, str): list = mem.split() if len(list) == 1: Exercise 7: Define a function sort_types that takes one argument: a list. This list has members that are of different types. Some members are just one word. Other members are texts with multiple words, some members are positive integers, some are negative integers, some are float numbers. The function returns a dictionary. The dictionary has the keys: words , longer texts , bools pos integers , neg integers and floats . The values associated to each key in the directory are lists consisting of all the members in the input list of that particular type. Example: sort_types([ will , -7, 0.22, False, You can , 5, 0, -0.34, True, maybe , no way! ]) returns the dictionary { words : [ will , maybe ], longer texts : [ You can , no way! ], bools : [False, True] pos integers : [5,0], neg integers : [-7], floats : [0.22, -0.34]} type_dir["words"].append(mem) else: type_dir["longer texts"].append(mem) elif isinstance(mem, bool): type_dir["bools"].append(mem) elif isinstance(mem, int): if mem >= 0: type_dir["pos integers"].append(mem) else: type_dir["neg integers"].append(mem) else: type_dir["floats"].append(mem) return type_dir - Create a dictionary of the required form, but with empty lists as values. Then loop over the input list and add to the appropriate key-value.

  13. Exercise 8: Define a function build_sentences, that takes one argument: a directory. An example of the directory is the following: Sentence_dir = { article : [ This , The , A , An ], noun1 : [ sentence , eggs , monty , exam ], verb : [ is , are , writes , could be ] adjective : [ wonderful , fine , clean , great ] noun2 : [ spam , stuff , Python , fun ] } The function should print a number of sentences to the screen. Each sentence is on a different line. The sentences are built by first taking the first article, first noun1, first verb, first adjective, first noun2, bringing them together in one text string and adding . at the end. The next sentences are built similarly, by taking the next members of the lists. For the example, the printed output should be This sentence is wonderful spam. The eggs are fine stuff. A monty writes clean Python. An exam could be great fun. Next, define a variant of this function, invent_sentences, taking again a dictionary as its one argument. This function should print 10 sentences, each on one line. Each sentence is built by independently selecting a random particle, a random noun1, a random verb, a random adjective and a random noun2 from the given dictionary and bring them in a new sentence. The sentences do not need to be grammatically correct. print real_sentence def build_sentences(dir): for i in range(len(dir["article"])): sentence_list = [dir["article"][i], dir["noun1"][i], dir["verb"][i], dir["adjective"][i], dir["noun2"][i]] sentence = " ".join(sentence_list) real_sentence = sentence + "." print real_sentence from random import randint def invent_sentences(dir): leng = len(dir["article"]) - 1 for i in range(10): sentence_list = [dir["article"][randint(0,leng)], dir["noun1"][randint(0,leng)], dir["verb"][randint(0,leng)], dir["adjective"][randint(0,leng)], dir["noun2"][randint(0,leng)] sentence = " ".join(sentence_list) real_sentence = sentence + "."

  14. CodeCademy 11.a: Introduction to Classes (50 min.) CodeCademy 11.b: Classes (Car) (20 min.) Exercise from LPTHW: Optional ! (depends on your time spent on CC) Just reading and understanding: ex.40 (10 min.), ex. 41 (30 min.) 14

Related


More Related Content