├── .gitignore ├── 001 ├── exercise001.go └── exercise001_test.go ├── 002 ├── exercise002.go └── exercise002_test.go ├── 003 ├── exercise003.go └── exercise003_test.go ├── 004 ├── exercise004.go └── exercise004_test.go ├── 005 ├── exercise005.go └── exercise005_main.go ├── 006 ├── exercise006.go └── exercise006_test.go ├── 007 ├── exercise007.go └── exercise007_test.go ├── 008 ├── exercise008.go └── exercise008_test.go ├── 009 ├── exercise009.go └── exercise009_test.go ├── 010 ├── exercise010.go └── exercise010_test.go ├── 011 ├── exercise011.go └── exercise011_test.go ├── 012 ├── exercise012.go └── exercise012_test.go ├── 013 ├── exercise013.go └── exercise013_test.go ├── LICENSE ├── README.adoc ├── exercises_advanced.adoc ├── exercises_beginner.adoc ├── exercises_intermediate.adoc ├── exercises_to_rewrite.txt └── go.mod /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .vscode/launch.json 3 | -------------------------------------------------------------------------------- /001/exercise001.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | Exercise 001: 5 | 6 | Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. 7 | */ 8 | 9 | import ( 10 | "fmt" 11 | "strconv" 12 | "strings" 13 | ) 14 | 15 | func main() { 16 | fmt.Println("Exercise 001") 17 | 18 | res := Ex001(2000, 3200) 19 | 20 | fmt.Println(res) 21 | 22 | } 23 | 24 | // Ex001 returns a slice of numbers 25 | func Ex001(low, high int) string { 26 | var numbers []string 27 | for i := low; i <= high; i++ { 28 | if i%7 == 0 && i%5 != 0 { 29 | numbers = append(numbers, strconv.Itoa(i)) 30 | } 31 | } 32 | return strings.Join(numbers, ",") 33 | } 34 | -------------------------------------------------------------------------------- /001/exercise001_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestEx001(t *testing.T) { 8 | 9 | want := "112,119,126,133,147,154,161,168,182,189,196" 10 | got := Ex001(100, 200) 11 | 12 | if got != want { 13 | t.Errorf("Ex001() = %v, want %v", got, want) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /002/exercise002.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. 5 | 6 | Suppose the following input is supplied to the program: 8 7 | Then, the output should be: 40320 8 | */ 9 | 10 | import ( 11 | "fmt" 12 | "log" 13 | ) 14 | 15 | func main() { 16 | fmt.Println("Exercise 002") 17 | 18 | // reading input from console 19 | var input int 20 | fmt.Print("Please enter a number : ") 21 | _, err := fmt.Scanln(&input) 22 | 23 | // checking for error and low 0 24 | if err != nil { 25 | log.Fatal("Please enter a number") 26 | } 27 | 28 | result, err := Ex002(input) 29 | 30 | if err != nil { 31 | log.Fatalf("Error for input %v: %v", input, err) 32 | } 33 | 34 | fmt.Printf("Factorial of %d = %d", input, result) 35 | } 36 | 37 | // Ex002 returns a factorial of input 38 | // if input == 0 returns 1 as per definition 39 | // if input < 0 returns 0 and an error 40 | func Ex002(input int) (uint64, error) { 41 | // uint64 because it can get big 42 | var factorial uint64 = 1 43 | 44 | if input < 0 { 45 | return 0, fmt.Errorf("factorial for negativ values is not allowed") 46 | } 47 | 48 | if input == 0 { 49 | return 1, nil 50 | } 51 | 52 | for i := 1; i <= input; i++ { 53 | factorial *= uint64(i) 54 | } 55 | return factorial, nil 56 | } 57 | -------------------------------------------------------------------------------- /002/exercise002_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestEx002(t *testing.T) { 8 | 9 | // check for error 10 | want := 0 11 | got, err := Ex002(-10) 12 | if err == nil { 13 | t.Errorf("Ex002() = %v, want %v", got, err) 14 | } 15 | 16 | want = 1 17 | got, err = Ex002(0) 18 | if err == nil && got != uint64(want) { 19 | t.Errorf("Expected '%v' but got '%v'", 1, got) 20 | } 21 | 22 | want = 40320 23 | got, err = Ex002(8) 24 | if err == nil && got != uint64(want) { 25 | t.Errorf("Ex002() = %v, want %v", got, want) 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /003/exercise003.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | Exercise 003 5 | 6 | With a given integral number n, write a program to generate a map that contains (i, i*i) such that is an integral number between 1 and n (both included), and then the program should print the map with representation of the value 7 | 8 | Suppose the following input is supplied to the program: 8 9 | Then, the output should be: 10 | map[1:1 2:4 3:9 4:16 5:25 6:36 7:49 8:64] 11 | 12 | */ 13 | 14 | import ( 15 | "fmt" 16 | "log" 17 | ) 18 | 19 | func main() { 20 | fmt.Println("Exercise 003") 21 | var n int 22 | fmt.Print("Enter a number: ") 23 | _, err := fmt.Scanln(&n) 24 | if err != nil { 25 | log.Fatal("Error occured: ", err) 26 | } 27 | 28 | fmt.Printf("%v", Ex003(n)) 29 | } 30 | 31 | // Ex003 returns a map with numbers are their squared values 32 | func Ex003(n int) map[int]int { 33 | // create a map with the size of n 34 | var numbers = make(map[int]int, n) 35 | 36 | for i := 1; i <= n; i++ { 37 | numbers[i] = i * i 38 | } 39 | return numbers 40 | } 41 | -------------------------------------------------------------------------------- /003/exercise003_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestEx004(t *testing.T) { 9 | 10 | input := 8 11 | want := map[int]int{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} 12 | got := Ex003(input) 13 | 14 | if !reflect.DeepEqual(got, want) { 15 | t.Errorf("Ex003() = %v, want %v", got, want) 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /004/exercise004.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | ) 7 | 8 | // Ex004 takes a string of comma-separated numbers and returns a slice of int 9 | func Ex004(input string) []int { 10 | // create a map with the size of n 11 | numbers := strings.Split(input, ",") 12 | 13 | length := len(numbers) 14 | var num = make([]int, length) 15 | 16 | for index, v := range numbers { 17 | s := strings.Trim(v, " ") 18 | num[index], _ = strconv.Atoi(s) 19 | } 20 | return num 21 | } 22 | -------------------------------------------------------------------------------- /004/exercise004_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestEx004(t *testing.T) { 9 | 10 | input := "12, 23, 34, 45, 56, 67, 78, 89, 90" 11 | want := []int{12, 23, 34, 45, 56, 67, 78, 89, 90} 12 | got := Ex004(input) 13 | 14 | if !reflect.DeepEqual(got, want) { 15 | t.Errorf("Ex004() = %v, want %v", got, want) 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /005/exercise005.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | Create a separate file (module) which has at least two methods: 5 | 6 | - ReadString: to read a string from console input 7 | - PrintString: to return the string in upper case. 8 | 9 | Also create a `main.go` file that acts as calling class. 10 | */ 11 | 12 | import ( 13 | "bufio" 14 | "os" 15 | "strings" 16 | ) 17 | 18 | var input string = "" 19 | 20 | // ReadString reads user input from command line, terminated via 'enter' 21 | func ReadString() { 22 | scanner := bufio.NewScanner(os.Stdin) 23 | if scanner.Scan() { 24 | input = scanner.Text() 25 | } 26 | } 27 | 28 | // PrintString prints the string entered via GetString 29 | func PrintString() string { 30 | return strings.ToUpper(input) 31 | } 32 | -------------------------------------------------------------------------------- /005/exercise005_main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | 9 | want := "HELLO WORLD!" 10 | 11 | ReadString() 12 | got := PrintString() 13 | //got = "afdsas" 14 | 15 | if got != want { 16 | fmt.Println(fmt.Errorf("Error: Ex005() = %v, want %v", got, want)) 17 | return 18 | } 19 | 20 | fmt.Println(got) 21 | 22 | } 23 | -------------------------------------------------------------------------------- /006/exercise006.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | const c = 50 6 | const h = 30 7 | 8 | // Ex006 calculates Q based on C=50 and H=50 9 | // Formula used: Q = Square root of [(2 * C * D)/H] 10 | func Ex006(d []int) []int { 11 | var s = make([]int, len(d)) 12 | 13 | for i, num := range d { 14 | a := (2 * c * num) / h 15 | q := math.Sqrt(float64(a)) 16 | 17 | var b int = int(math.Round(q)) 18 | 19 | s[i] = b 20 | } 21 | 22 | return s 23 | } 24 | -------------------------------------------------------------------------------- /006/exercise006_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | // TestEx006 test if Ex006 does correct calculation of 9 | // Q = Square root of [(2 * C * D)/H] 10 | func TestEx006(t *testing.T) { 11 | 12 | input := []int{100, 150, 180} 13 | want := []int{18, 22, 24} 14 | got := Ex006(input) 15 | 16 | if !reflect.DeepEqual(got, want) { 17 | t.Errorf("Ex006() = %v, want %v", got, want) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /007/exercise007.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // Ex007 takes two numbers and generate a slice 4 | // Then, the output of the program should be: 5 | // [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 6 | func Ex007(x, y int) [][]int { 7 | 8 | slice := [][]int{} 9 | 10 | for i := 0; i < x; i++ { 11 | 12 | row := []int{} 13 | for j := 0; j < y; j++ { 14 | p := i * j 15 | row = append(row, p) 16 | } 17 | slice = append(slice, row) 18 | } 19 | 20 | return slice 21 | } 22 | -------------------------------------------------------------------------------- /007/exercise007_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | // TestEx006 test if Ex006 does correct calculation of 9 | // Q = Square root of [(2 * C * D)/H] 10 | func TestEx007(t *testing.T) { 11 | 12 | a := 3 13 | b := 5 14 | want := [][]int{{0, 0, 0, 0, 0}, {0, 1, 2, 3, 4}, {0, 2, 4, 6, 8}} 15 | got := Ex007(a, b) 16 | 17 | if !reflect.DeepEqual(got, want) { 18 | t.Errorf("Ex007() = %v, want %v", got, want) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /008/exercise008.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strings" 4 | 5 | // Ex008 takes two numbers and generate a slice 6 | // Input: without,hello,bag,world 7 | // Output: bag,hello,without,world 8 | func Ex008(input string) string { 9 | 10 | output := "" 11 | 12 | slice := strings.Split(input, ",") 13 | // sorting 14 | sorted := true 15 | 16 | for sorted { 17 | sorted = false 18 | for l := len(slice) - 1; l > 0; l-- { 19 | if slice[l] < slice[l-1] { 20 | slice[l], slice[l-1] = slice[l-1], slice[l] 21 | sorted = true 22 | } 23 | } 24 | } 25 | 26 | output = strings.Join(slice, ",") 27 | 28 | return output 29 | } 30 | -------------------------------------------------------------------------------- /008/exercise008_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | // Write a program that accepts a comma separated sequence of words as input 9 | // and prints the words in a comma-separated sequence after sorting them 10 | // alphabetically. 11 | func TestEx008(t *testing.T) { 12 | 13 | input := "without,hello,bag,world" 14 | want := "bag,hello,without,world" 15 | 16 | got := Ex008(input) 17 | 18 | if !reflect.DeepEqual(got, want) { 19 | t.Errorf("Ex008() = %v, want %v", got, want) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /009/exercise009.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strings" 4 | 5 | // Ex009 convert input to upper case 6 | func Ex009(input []string) []string { 7 | 8 | output := []string{} 9 | 10 | for _, v := range input { 11 | output = append(output, strings.ToUpper(v)) 12 | } 13 | 14 | return output 15 | } 16 | -------------------------------------------------------------------------------- /009/exercise009_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | // Write a program that accepts sequence of lines as input and prints the lines 9 | // after making all characters in the sentence capitalized. 10 | func TestEx009(t *testing.T) { 11 | 12 | input := []string{"Hello world", "Practice makes perfect"} 13 | want := []string{"HELLO WORLD", "PRACTICE MAKES PERFECT"} 14 | 15 | got := Ex009(input) 16 | 17 | if !reflect.DeepEqual(got, want) { 18 | t.Errorf("Ex009() = %v, want %v", got, want) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /010/exercise010.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sort" 5 | "strings" 6 | ) 7 | 8 | // Ex010 accepts a String separated by whitespace. 9 | // input gets sorted and duplicates are removed 10 | func Ex010(input string) string { 11 | 12 | // make a map and split the input string 13 | m := make(map[string]bool) 14 | temp := strings.Split(input, " ") 15 | 16 | // add values to map as keys (making them unique) 17 | for _, v := range temp { 18 | m[v] = true 19 | } 20 | 21 | // convert map back into slice 22 | var result []string 23 | for key := range m { 24 | result = append(result, key) 25 | } 26 | 27 | // sort slice and join back toghether 28 | sort.Strings(result) 29 | output := strings.Join(result, " ") 30 | 31 | return output 32 | } 33 | -------------------------------------------------------------------------------- /010/exercise010_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | // Write a program that accepts a sequence of whitespace separated words as 9 | // input and prints the words after removing all duplicate words and sorting 10 | // them alphanumerically. 11 | func TestEx010(t *testing.T) { 12 | 13 | input := "hello world and practice makes perfect and hello world again" 14 | want := "again and hello makes perfect practice world" 15 | 16 | got := Ex010(input) 17 | 18 | if !reflect.DeepEqual(got, want) { 19 | t.Errorf("Ex010() = %v, want %v", got, want) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /011/exercise011.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | ) 7 | 8 | // Ex011 takes comma separated string with 4 digits binary numbers 9 | // returns a comma separated string which the numbers which can 10 | // be divided by 5 11 | func Ex011(input string) string { 12 | 13 | // split string 14 | numbers := strings.Split(input, ",") 15 | result := []string{} 16 | 17 | // loop over numbers 18 | for _, v := range numbers { 19 | // convert 20 | converted, _ := strconv.ParseInt(v, 2, 64) 21 | // if mod 5 == 0 22 | if converted%5 == 0 { 23 | // convert back to binary and add to result slice 24 | // s := strconv.FormatInt(converted, 2) 25 | // result = append(result, s) 26 | 27 | // just add v to the result 28 | result = append(result, v) 29 | } 30 | 31 | } 32 | // join output back together 33 | output := strings.Join(result, ",") 34 | 35 | return output 36 | } 37 | -------------------------------------------------------------------------------- /011/exercise011_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | // Write a program which accepts a sequence of comma separated 4 digit binary 9 | // numbers as its input and then check whether they are divisible by 5 or not. 10 | // The numbers that are divisible by 5 are to be printed in a comma 11 | // separated sequence. 12 | 13 | func TestEx011(t *testing.T) { 14 | 15 | input := "0100,0011,1010,1001" 16 | want := "1010" 17 | 18 | got := Ex011(input) 19 | 20 | if !reflect.DeepEqual(got, want) { 21 | t.Errorf("Ex011() = %v, want %v", got, want) 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /012/exercise012.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "strings" 7 | ) 8 | 9 | // Ex012 run over two numbers 10 | func Ex012(start, end int) string { 11 | 12 | values := []string{} 13 | 14 | // loop from start to end 15 | for num := int64(start); num < int64(end); num++ { 16 | temp := strconv.FormatInt(num, 10) 17 | 18 | a := int(temp[0]) 19 | b := int(temp[1]) 20 | c := int(temp[2]) 21 | 22 | if a%2 == 0 && b%2 == 0 && c%2 == 0 { 23 | values = append(values, fmt.Sprint(num)) 24 | } 25 | 26 | } 27 | return strings.Join(values, ",") 28 | } 29 | -------------------------------------------------------------------------------- /012/exercise012_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | // Write a program, which will find all such numbers 9 | // between 100 and 300 (both included) such that each digit of 10 | // the number is an even number. The numbers obtained should be printed 11 | // in a comma-separated sequence on a single line. 12 | 13 | func TestEx012(t *testing.T) { 14 | 15 | inputA := 100 16 | inputB := 300 17 | want := "200,202,204,206,208,220,222,224,226,228,240,242,244,246,248,260,262,264,266,268,280,282,284,286,288" 18 | 19 | got := Ex012(inputA, inputB) 20 | 21 | if !reflect.DeepEqual(got, want) { 22 | t.Errorf("\nEx012() = %v\nwant = %v", got, want) 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /013/exercise013.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "unicode" 6 | ) 7 | 8 | // Ex013 run over two numbers 9 | func Ex013(input string) string { 10 | 11 | var digits int = 0 12 | var letters int = 0 13 | 14 | for _, char := range input { 15 | if unicode.IsDigit(char) { 16 | digits++ 17 | } else if unicode.IsLetter(char) { 18 | letters++ 19 | } else { 20 | continue 21 | } 22 | } 23 | return fmt.Sprintf("LETTERS %v, DIGITS %v", letters, digits) 24 | } 25 | -------------------------------------------------------------------------------- /013/exercise013_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | // Write a program that accepts a sentence and calculate the number of letters and digits. 9 | 10 | func TestEx013(t *testing.T) { 11 | 12 | input := "hello world! 123" 13 | want := "LETTERS 10, DIGITS 3" 14 | 15 | got := Ex013(input) 16 | 17 | if !reflect.DeepEqual(got, want) { 18 | t.Errorf("\nEx013() = %v\nwant = %v", got, want) 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 cblte 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 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = 100+ challenging Golang programming exercises 2 | Carsten Brueggenolte 3 | v1.0.0, March 2021: Initial Document 4 | // Meta Data 5 | :description: Rewritten from the 100+ Python challenging programming exercises" 6 | :keywords: Golang, programming, exercises, challenges 7 | // Settings 8 | :icons: font 9 | :source-highlighter: highlightjs 10 | :url-project: https://github.com/cblte/100-golang-exercises/ 11 | :url-issues: {url-project}/issues 12 | 13 | 14 | These challenges come from a file called "100+ Python challenging programming exercises" I found somewhere on the internet. I want to rewrite all exercises for Golang! 15 | 16 | I will update the file along with me rewriting the solutions provided in Python. Furthermore, I will also put a file for each solution into a subdirectory, so it can be run locally. Some smaller single file solutions can also be run in the Golang playground (https://play.golang.org). 17 | 18 | This is also a training for myself to learn the language and to exercise writing code. I also want to write tests for most of the apps, because I think, tests are always forgotten, and I also should write more tests when writing code. 19 | 20 | The exercises for the different levels (see below) are split into the respective files. 21 | 22 | But before that, here are the links to the files: 23 | 24 | - Beginner: link:exercises_beginner.adoc[] 25 | - Intermediate: link:exercises_intermediate.adoc[] 26 | - Advanced: link:exercises_advanced.adoc[] 27 | 28 | 29 | == Level description 30 | 31 | Here is the original description of the python file for the different exercises. 32 | 33 | === Level 1 Beginner 34 | 35 | Beginner means someone who has just gone through an introductory Golang course. He can solve some problems with 1 or 2 Golang classes or functions. Normally, the answers could directly be found in the textbooks. 36 | 37 | === Level 2 Intermediate 38 | 39 | Intermediate means someone who has just learned Golang, but already has a relatively strong programming background from before. He should be able to solve problems which may involve 3 or 3 Golang classes or functions. The answers cannot be directly be found in the textbooks. 40 | 41 | === Level 3 Advanced 42 | 43 | Advanced means you should use Golang to solve more complex problem using more rich libraries functions and data structures and algorithms. The user is supposed to solve the problem using several Golang standard packages and advanced techniques. 44 | 45 | 46 | == Remark 47 | 48 | This repository is in no way complete and should be considered complete. I'm still learning the language go myself and there are still some bugs here and there. If you find one, please let me know. Gladly also by a pull request. 49 | 50 | Thanks -------------------------------------------------------------------------------- /exercises_advanced.adoc: -------------------------------------------------------------------------------- 1 | = Exercises for Beginners 2 | Carsten Brueggenolte 3 | v1.0.0, March 2021 4 | // Meta Data 5 | :description: Rewritten from the 100+ Python challenging programming exercises" 6 | :keywords: Golang, programming, exercises, challenges 7 | :toc: right 8 | // Settings 9 | :icons: font 10 | :source-highlighter: highlightjs 11 | :sectnums: 12 | :url-project: https://github.com/cblte/100-golang-exercises/ 13 | :url-issues: {url-project}/issues 14 | 15 | 16 | This document contains all the advanced exercises. If you find an error or a bug or something that could be written better, please get in contact with me. Thanks. -------------------------------------------------------------------------------- /exercises_beginner.adoc: -------------------------------------------------------------------------------- 1 | = Exercises for Beginners 2 | Carsten Brueggenolte 3 | v1.0.0, March 2021 4 | // Meta Data 5 | :description: Rewritten from the 100+ Python challenging programming exercises" 6 | :keywords: Golang, programming, exercises, challenges 7 | :toc: auto 8 | :toclevels: 1 9 | // Settings 10 | :icons: font 11 | :source-highlighter: highlightjs 12 | :sectnums: 13 | :url-project: https://github.com/cblte/100-golang-exercises/ 14 | :url-issues: {url-project}/issues 15 | 16 | 17 | This document contains all the beginner exercises. If you find an error or a bug or something that could be written better, please get in contact with me. Thanks. 18 | 19 | == Exercise 001: Find numbers devisable by 7 but not by 5 20 | 21 | Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. 22 | 23 | === Hint: 24 | Consider using strconv and strings.Join 25 | 26 | === Solution: 27 | link:001/exercise001.go[] 28 | 29 | 30 | == Exercise 002: Compute factorial 31 | 32 | .Exercise Description 33 | Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. 34 | 35 | Suppose the following input is supplied to the program: `8` 36 | 37 | Then, the output should be: `40320` 38 | 39 | === Hints: 40 | In case of input data being supplied to the question, it should be assumed to be a console input. 41 | 42 | === Solution: 43 | link:002/exercise002.go[] 44 | 45 | == Exercise 003 : Create a map with numbers squared 46 | 47 | With a given integral number n, write a program to generate a map that contains (i, i*i) such that is an integral number between 1 and n (both included), and then the program should print the map with representation of the value 48 | 49 | Suppose the following input is supplied to the program: `8` 50 | 51 | Then, the output should be: `map[1:1 2:4 3:9 4:16 5:25 6:36 7:49 8:64]` 52 | 53 | === Hints: 54 | Use `make` for the map and `%v` verb for the output. 55 | 56 | 57 | === Solution: 58 | link:003/exercise003.go[] 59 | 60 | 61 | == Exercise 004 : Create a slice from comma-seperated input string 62 | 63 | Write a program which accepts a sequence of comma-separated numbers from console and generate an slice out of them. Return the slice. 64 | 65 | Suppose the following input is supplied to the program: `34, 67, 55, 33, 12, 98`. 66 | 67 | Then, the output should be: `[34 67 55 33 12 98]` 68 | 69 | === Hints: 70 | In case of input data being supplied to the question, it should be assumed to be a console input. package `strings` has a split method. 71 | 72 | === Solution: 73 | link:004/exercise004.go[] 74 | 75 | 76 | == Exercise 005 : Define a "class" (interface) which has at least two methods 77 | 78 | Create a seperate file (module) which has at least two methods: 79 | 80 | - ReadString: to read a string from console input 81 | - PrintString: to return the string in upper case. 82 | 83 | Also create a `main.go` file that acts as calling class. 84 | 85 | === Hints 86 | - Use `bufio.NewScanner(os.Stdin)` to read in a full line of text. 87 | - user `go run .` to execute considering all files in the directory 88 | 89 | === Solution: 90 | link:005/exercise005.go[] -------------------------------------------------------------------------------- /exercises_intermediate.adoc: -------------------------------------------------------------------------------- 1 | = Exercises for Intermediate 2 | Carsten Brueggenolte 3 | v1.0.0, March 2021 4 | // Meta Data 5 | :description: Rewritten from the 100+ Python challenging programming exercises" 6 | :keywords: Golang, programming, exercises, challenges 7 | :toc: right 8 | // Settings 9 | :icons: font 10 | :source-highlighter: highlightjs 11 | :sectnums: 12 | :url-project: https://github.com/cblte/100-golang-exercises/ 13 | :url-issues: {url-project}/issues 14 | 15 | 16 | This document contains all the intermediate exercises. If you find an error or a bug or something that could be written better, please get in contact with me. Thanks. 17 | 18 | == Exercise 006 19 | 20 | Write a program that calculates and prints the value according to the given formula: 21 | 22 | Q = Square root of [(2 * C * D)/H] 23 | 24 | Following are the fixed values of C and H: 25 | 26 | - C is 50. H is 30. 27 | - D is the variable whose values should be input to your program in a comma-separated sequence. 28 | 29 | Example: 30 | 31 | Let us assume the following comma separated input sequence is given to the program: 100,150,180 32 | 33 | The output of the program should be: 18,22,24 34 | 35 | === Hints: 36 | 37 | - use `math.Sqrt` for the square root 38 | - use `math.Round` for rounding a float operation 39 | 40 | == Solution: 41 | 42 | link:006/exercise006.go[] 43 | 44 | 45 | == Exercise 007 46 | 47 | Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. 48 | Note: i=0,1.., X-1; j=0,1,¡­Y-1. 49 | 50 | Example 51 | 52 | Suppose the following inputs are given to the program: 3,5 53 | 54 | Then, the output of the program should be: 55 | [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 56 | 57 | === Hints: 58 | Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. 59 | 60 | === Solution: 61 | 62 | link:007/exercise007.go[] 63 | 64 | == Exercise 008 65 | 66 | Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. 67 | 68 | Suppose the following input is supplied to the program: 69 | 70 | without,hello,bag,world 71 | 72 | Then, the output should be: 73 | 74 | bag,hello,without,world 75 | 76 | === Hints: 77 | 78 | In case of input data being supplied to the question, it should be assumed to be a console input. 79 | 80 | === Solution: 81 | 82 | link:008/exercise008.go[] 83 | 84 | 85 | == Exercise 009 86 | 87 | Write a program that accepts sequence of lines as input and prints the lines 88 | after making all characters in the sentence capitalized. 89 | 90 | Suppose the following input is supplied to the program: 91 | 92 | Hello world 93 | Practice makes perfect 94 | 95 | Then, the output should be: 96 | 97 | HELLO WORLD 98 | PRACTICE MAKES PERFECT 99 | 100 | === Hints 101 | In case of input data being supplied to the question, it should be assumed to be a console input. 102 | 103 | === Solution: 104 | 105 | link:009/exercise009.go[] 106 | 107 | 108 | == Exercise 009 109 | 110 | Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. 111 | 112 | Suppose the following input is supplied to the program: 113 | 114 | hello world and practice makes perfect and hello world again 115 | 116 | Then, the output should be: 117 | 118 | again and hello makes perfect practice world 119 | 120 | === Hints 121 | 122 | In case of input data being supplied to the question, it should be assumed to be a console input. 123 | We use set container to remove duplicated data automatically and then use sorted() to sort the data. 124 | 125 | == Solution: 126 | 127 | link:010/exercise010.go[] 128 | 129 | 130 | == Exercise 011 131 | 132 | Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. 133 | 134 | Example: 135 | 0100,0011,1010,1001 136 | 137 | Then the output should be: 138 | 1010 139 | 140 | Notes: Assume the data is input by console. 141 | 142 | === Hints: 143 | 144 | In case of input data being supplied to the question, it should be assumed to be a console input. 145 | 146 | === Solution: 147 | 148 | link:011/exercise011.go[] 149 | 150 | 151 | == Exercise 012 152 | 153 | Write a program, which will find all such numbers between 100 and 300 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. 154 | 155 | === Hints: 156 | In case of input data being supplied to the question, it should be assumed to be a console input. 157 | 158 | 159 | === Solution: 160 | 161 | link:012/exercise012.go[] 162 | 163 | 164 | == Exercise 013 165 | 166 | Write a program that accepts a sentence and calculate the number of letters and digits. 167 | 168 | Suppose the following input is supplied to the program: 169 | 170 | hello world! 123 171 | 172 | Then, the output should be: 173 | 174 | LETTERS 10 175 | DIGITS 3 176 | 177 | === Hints: 178 | In case of input data being supplied to the question, it should be assumed to be a console input. 179 | 180 | === Solution: 181 | 182 | link:013/exercise013.go[] -------------------------------------------------------------------------------- /exercises_to_rewrite.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | #----------------------------------------# 4 | 5 | #----------------------------------------# 6 | 7 | #----------------------------------------# 8 | 9 | #----------------------------------------# 10 | 11 | #----------------------------------------# 12 | 13 | #----------------------------------------# 14 | 15 | #----------------------------------------# 16 | 17 | #----------------------------------------# 18 | 19 | #----------------------------------------# 20 | 21 | #----------------------------------------# 22 | 23 | #----------------------------------------# 24 | Question 14 25 | Level 2 26 | 27 | Question: 28 | Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. 29 | Suppose the following input is supplied to the program: 30 | Hello world! 31 | Then, the output should be: 32 | UPPER CASE 1 33 | LOWER CASE 9 34 | 35 | Hints: 36 | In case of input data being supplied to the question, it should be assumed to be a console input. 37 | 38 | Solution: 39 | s = raw_input() 40 | d={"UPPER CASE":0, "LOWER CASE":0} 41 | for c in s: 42 | if c.isupper(): 43 | d["UPPER CASE"]+=1 44 | elif c.islower(): 45 | d["LOWER CASE"]+=1 46 | else: 47 | pass 48 | print "UPPER CASE", d["UPPER CASE"] 49 | print "LOWER CASE", d["LOWER CASE"] 50 | #----------------------------------------# 51 | 52 | #----------------------------------------# 53 | Question 15 54 | Level 2 55 | 56 | Question: 57 | Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. 58 | Suppose the following input is supplied to the program: 59 | 9 60 | Then, the output should be: 61 | 11106 62 | 63 | Hints: 64 | In case of input data being supplied to the question, it should be assumed to be a console input. 65 | 66 | Solution: 67 | a = raw_input() 68 | n1 = int( "%s" % a ) 69 | n2 = int( "%s%s" % (a,a) ) 70 | n3 = int( "%s%s%s" % (a,a,a) ) 71 | n4 = int( "%s%s%s%s" % (a,a,a,a) ) 72 | print n1+n2+n3+n4 73 | #----------------------------------------# 74 | 75 | #----------------------------------------# 76 | Question 16 77 | Level 2 78 | 79 | Question: 80 | Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. 81 | Suppose the following input is supplied to the program: 82 | 1,2,3,4,5,6,7,8,9 83 | Then, the output should be: 84 | 1,3,5,7,9 85 | 86 | Hints: 87 | In case of input data being supplied to the question, it should be assumed to be a console input. 88 | 89 | Solution: 90 | values = raw_input() 91 | numbers = [x for x in values.split(",") if int(x)%2!=0] 92 | print ",".join(numbers) 93 | #----------------------------------------# 94 | 95 | Question 17 96 | Level 2 97 | 98 | Question: 99 | Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: 100 | D 100 101 | W 200 102 | 103 | D means deposit while W means withdrawal. 104 | Suppose the following input is supplied to the program: 105 | D 300 106 | D 300 107 | W 200 108 | D 100 109 | Then, the output should be: 110 | 500 111 | 112 | Hints: 113 | In case of input data being supplied to the question, it should be assumed to be a console input. 114 | 115 | Solution: 116 | netAmount = 0 117 | while True: 118 | s = raw_input() 119 | if not s: 120 | break 121 | values = s.split(" ") 122 | operation = values[0] 123 | amount = int(values[1]) 124 | if operation=="D": 125 | netAmount+=amount 126 | elif operation=="W": 127 | netAmount-=amount 128 | else: 129 | pass 130 | print netAmount 131 | #----------------------------------------# 132 | 133 | #----------------------------------------# 134 | Question 18 135 | Level 3 136 | 137 | Question: 138 | A website requires the users to input username and password to register. Write a program to check the validity of password input by users. 139 | Following are the criteria for checking the password: 140 | 1. At least 1 letter between [a-z] 141 | 2. At least 1 number between [0-9] 142 | 1. At least 1 letter between [A-Z] 143 | 3. At least 1 character from [$#@] 144 | 4. Minimum length of transaction password: 6 145 | 5. Maximum length of transaction password: 12 146 | Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. 147 | Example 148 | If the following passwords are given as input to the program: 149 | ABd1234@1,a F1#,2w3E*,2We3345 150 | Then, the output of the program should be: 151 | ABd1234@1 152 | 153 | Hints: 154 | In case of input data being supplied to the question, it should be assumed to be a console input. 155 | 156 | Solutions: 157 | import re 158 | value = [] 159 | items=[x for x in raw_input().split(',')] 160 | for p in items: 161 | if len(p)<6 or len(p)>12: 162 | continue 163 | else: 164 | pass 165 | if not re.search("[a-z]",p): 166 | continue 167 | elif not re.search("[0-9]",p): 168 | continue 169 | elif not re.search("[A-Z]",p): 170 | continue 171 | elif not re.search("[$#@]",p): 172 | continue 173 | elif re.search("\s",p): 174 | continue 175 | else: 176 | pass 177 | value.append(p) 178 | print ",".join(value) 179 | #----------------------------------------# 180 | 181 | #----------------------------------------# 182 | Question 19 183 | Level 3 184 | 185 | Question: 186 | You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: 187 | 1: Sort based on name; 188 | 2: Then sort based on age; 189 | 3: Then sort by score. 190 | The priority is that name > age > score. 191 | If the following tuples are given as input to the program: 192 | Tom,19,80 193 | John,20,90 194 | Jony,17,91 195 | Jony,17,93 196 | Json,21,85 197 | Then, the output of the program should be: 198 | [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] 199 | 200 | Hints: 201 | In case of input data being supplied to the question, it should be assumed to be a console input. 202 | We use itemgetter to enable multiple sort keys. 203 | 204 | Solutions: 205 | from operator import itemgetter, attrgetter 206 | 207 | l = [] 208 | while True: 209 | s = raw_input() 210 | if not s: 211 | break 212 | l.append(tuple(s.split(","))) 213 | 214 | print sorted(l, key=itemgetter(0,1,2)) 215 | #----------------------------------------# 216 | 217 | #----------------------------------------# 218 | Question 20 219 | Level 3 220 | 221 | Question: 222 | Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. 223 | 224 | Hints: 225 | Consider use yield 226 | 227 | Solution: 228 | def putNumbers(n): 229 | i = 0 230 | while ilen2: 491 | print s1 492 | elif len2>len1: 493 | print s2 494 | else: 495 | print s1 496 | print s2 497 | 498 | 499 | printValue("one","three") 500 | 501 | 502 | 503 | #----------------------------------------# 504 | 2.10 505 | 506 | Question: 507 | Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number". 508 | 509 | Hints: 510 | 511 | Use % operator to check if a number is even or odd. 512 | 513 | Solution 514 | def checkValue(n): 515 | if n%2 == 0: 516 | print "It is an even number" 517 | else: 518 | print "It is an odd number" 519 | 520 | 521 | checkValue(7) 522 | 523 | 524 | #----------------------------------------# 525 | 2.10 526 | 527 | Question: 528 | Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. 529 | 530 | Hints: 531 | 532 | Use dict[key]=value pattern to put entry into a dictionary. 533 | Use ** operator to get power of a number. 534 | 535 | Solution 536 | def printDict(): 537 | d=dict() 538 | d[1]=1 539 | d[2]=2**2 540 | d[3]=3**2 541 | print d 542 | 543 | 544 | printDict() 545 | 546 | 547 | 548 | 549 | 550 | #----------------------------------------# 551 | 2.10 552 | 553 | Question: 554 | Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. 555 | 556 | Hints: 557 | 558 | Use dict[key]=value pattern to put entry into a dictionary. 559 | Use ** operator to get power of a number. 560 | Use range() for loops. 561 | 562 | Solution 563 | def printDict(): 564 | d=dict() 565 | for i in range(1,21): 566 | d[i]=i**2 567 | print d 568 | 569 | 570 | printDict() 571 | 572 | 573 | #----------------------------------------# 574 | 2.10 575 | 576 | Question: 577 | Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only. 578 | 579 | Hints: 580 | 581 | Use dict[key]=value pattern to put entry into a dictionary. 582 | Use ** operator to get power of a number. 583 | Use range() for loops. 584 | Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. 585 | 586 | Solution 587 | def printDict(): 588 | d=dict() 589 | for i in range(1,21): 590 | d[i]=i**2 591 | for (k,v) in d.items(): 592 | print v 593 | 594 | 595 | printDict() 596 | 597 | #----------------------------------------# 598 | 2.10 599 | 600 | Question: 601 | Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only. 602 | 603 | Hints: 604 | 605 | Use dict[key]=value pattern to put entry into a dictionary. 606 | Use ** operator to get power of a number. 607 | Use range() for loops. 608 | Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. 609 | 610 | Solution 611 | def printDict(): 612 | d=dict() 613 | for i in range(1,21): 614 | d[i]=i**2 615 | for k in d.keys(): 616 | print k 617 | 618 | 619 | printDict() 620 | 621 | 622 | #----------------------------------------# 623 | 2.10 624 | 625 | Question: 626 | Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). 627 | 628 | Hints: 629 | 630 | Use ** operator to get power of a number. 631 | Use range() for loops. 632 | Use list.append() to add values into a list. 633 | 634 | Solution 635 | def printList(): 636 | li=list() 637 | for i in range(1,21): 638 | li.append(i**2) 639 | print li 640 | 641 | 642 | printList() 643 | 644 | #----------------------------------------# 645 | 2.10 646 | 647 | Question: 648 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. 649 | 650 | Hints: 651 | 652 | Use ** operator to get power of a number. 653 | Use range() for loops. 654 | Use list.append() to add values into a list. 655 | Use [n1:n2] to slice a list 656 | 657 | Solution 658 | def printList(): 659 | li=list() 660 | for i in range(1,21): 661 | li.append(i**2) 662 | print li[:5] 663 | 664 | 665 | printList() 666 | 667 | 668 | #----------------------------------------# 669 | 2.10 670 | 671 | Question: 672 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. 673 | 674 | Hints: 675 | 676 | Use ** operator to get power of a number. 677 | Use range() for loops. 678 | Use list.append() to add values into a list. 679 | Use [n1:n2] to slice a list 680 | 681 | Solution 682 | def printList(): 683 | li=list() 684 | for i in range(1,21): 685 | li.append(i**2) 686 | print li[-5:] 687 | 688 | 689 | printList() 690 | 691 | 692 | #----------------------------------------# 693 | 2.10 694 | 695 | Question: 696 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. 697 | 698 | Hints: 699 | 700 | Use ** operator to get power of a number. 701 | Use range() for loops. 702 | Use list.append() to add values into a list. 703 | Use [n1:n2] to slice a list 704 | 705 | Solution 706 | def printList(): 707 | li=list() 708 | for i in range(1,21): 709 | li.append(i**2) 710 | print li[5:] 711 | 712 | 713 | printList() 714 | 715 | 716 | #----------------------------------------# 717 | 2.10 718 | 719 | Question: 720 | Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). 721 | 722 | Hints: 723 | 724 | Use ** operator to get power of a number. 725 | Use range() for loops. 726 | Use list.append() to add values into a list. 727 | Use tuple() to get a tuple from a list. 728 | 729 | Solution 730 | def printTuple(): 731 | li=list() 732 | for i in range(1,21): 733 | li.append(i**2) 734 | print tuple(li) 735 | 736 | printTuple() 737 | 738 | 739 | 740 | #----------------------------------------# 741 | 2.10 742 | 743 | Question: 744 | With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line. 745 | 746 | Hints: 747 | 748 | Use [n1:n2] notation to get a slice from a tuple. 749 | 750 | Solution 751 | tp=(1,2,3,4,5,6,7,8,9,10) 752 | tp1=tp[:5] 753 | tp2=tp[5:] 754 | print tp1 755 | print tp2 756 | 757 | 758 | #----------------------------------------# 759 | 2.10 760 | 761 | Question: 762 | Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). 763 | 764 | Hints: 765 | 766 | Use "for" to iterate the tuple 767 | Use tuple() to generate a tuple from a list. 768 | 769 | Solution 770 | tp=(1,2,3,4,5,6,7,8,9,10) 771 | li=list() 772 | for i in tp: 773 | if tp[i]%2==0: 774 | li.append(tp[i]) 775 | 776 | tp2=tuple(li) 777 | print tp2 778 | 779 | 780 | 781 | #----------------------------------------# 782 | 2.14 783 | 784 | Question: 785 | Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". 786 | 787 | Hints: 788 | 789 | Use if statement to judge condition. 790 | 791 | Solution 792 | s= raw_input() 793 | if s=="yes" or s=="YES" or s=="Yes": 794 | print "Yes" 795 | else: 796 | print "No" 797 | 798 | 799 | 800 | #----------------------------------------# 801 | 3.4 802 | 803 | Question: 804 | Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10]. 805 | 806 | Hints: 807 | 808 | Use filter() to filter some elements in a list. 809 | Use lambda to define anonymous functions. 810 | 811 | Solution 812 | li = [1,2,3,4,5,6,7,8,9,10] 813 | evenNumbers = filter(lambda x: x%2==0, li) 814 | print evenNumbers 815 | 816 | 817 | #----------------------------------------# 818 | 3.4 819 | 820 | Question: 821 | Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. 822 | 823 | Hints: 824 | 825 | Use map() to generate a list. 826 | Use lambda to define anonymous functions. 827 | 828 | Solution 829 | li = [1,2,3,4,5,6,7,8,9,10] 830 | squaredNumbers = map(lambda x: x**2, li) 831 | print squaredNumbers 832 | 833 | #----------------------------------------# 834 | 3.5 835 | 836 | Question: 837 | Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]. 838 | 839 | Hints: 840 | 841 | Use map() to generate a list. 842 | Use filter() to filter elements of a list. 843 | Use lambda to define anonymous functions. 844 | 845 | Solution 846 | li = [1,2,3,4,5,6,7,8,9,10] 847 | evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) 848 | print evenNumbers 849 | 850 | 851 | 852 | 853 | #----------------------------------------# 854 | 3.5 855 | 856 | Question: 857 | Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). 858 | 859 | Hints: 860 | 861 | Use filter() to filter elements of a list. 862 | Use lambda to define anonymous functions. 863 | 864 | Solution 865 | evenNumbers = filter(lambda x: x%2==0, range(1,21)) 866 | print evenNumbers 867 | 868 | 869 | #----------------------------------------# 870 | 3.5 871 | 872 | Question: 873 | Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). 874 | 875 | Hints: 876 | 877 | Use map() to generate a list. 878 | Use lambda to define anonymous functions. 879 | 880 | Solution 881 | squaredNumbers = map(lambda x: x**2, range(1,21)) 882 | print squaredNumbers 883 | 884 | 885 | 886 | 887 | #----------------------------------------# 888 | 7.2 889 | 890 | Question: 891 | Define a class named American which has a static method called printNationality. 892 | 893 | Hints: 894 | 895 | Use @staticmethod decorator to define class static method. 896 | 897 | Solution 898 | class American(object): 899 | @staticmethod 900 | def printNationality(): 901 | print "America" 902 | 903 | anAmerican = American() 904 | anAmerican.printNationality() 905 | American.printNationality() 906 | 907 | 908 | 909 | 910 | #----------------------------------------# 911 | 912 | 7.2 913 | 914 | Question: 915 | Define a class named American and its subclass NewYorker. 916 | 917 | Hints: 918 | 919 | Use class Subclass(ParentClass) to define a subclass. 920 | 921 | Solution: 922 | 923 | class American(object): 924 | pass 925 | 926 | class NewYorker(American): 927 | pass 928 | 929 | anAmerican = American() 930 | aNewYorker = NewYorker() 931 | print anAmerican 932 | print aNewYorker 933 | 934 | 935 | 936 | 937 | #----------------------------------------# 938 | 939 | 940 | 7.2 941 | 942 | Question: 943 | Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. 944 | 945 | Hints: 946 | 947 | Use def methodName(self) to define a method. 948 | 949 | Solution: 950 | 951 | class Circle(object): 952 | def __init__(self, r): 953 | self.radius = r 954 | 955 | def area(self): 956 | return self.radius**2*3.14 957 | 958 | aCircle = Circle(2) 959 | print aCircle.area() 960 | 961 | 962 | 963 | 964 | 965 | 966 | #----------------------------------------# 967 | 968 | 7.2 969 | 970 | Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. 971 | 972 | Hints: 973 | 974 | Use def methodName(self) to define a method. 975 | 976 | Solution: 977 | 978 | class Rectangle(object): 979 | def __init__(self, l, w): 980 | self.length = l 981 | self.width = w 982 | 983 | def area(self): 984 | return self.length*self.width 985 | 986 | aRectangle = Rectangle(2,10) 987 | print aRectangle.area() 988 | 989 | 990 | 991 | 992 | #----------------------------------------# 993 | 994 | 7.2 995 | 996 | Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. 997 | 998 | Hints: 999 | 1000 | To override a method in super class, we can define a method with the same name in the super class. 1001 | 1002 | Solution: 1003 | 1004 | class Shape(object): 1005 | def __init__(self): 1006 | pass 1007 | 1008 | def area(self): 1009 | return 0 1010 | 1011 | class Square(Shape): 1012 | def __init__(self, l): 1013 | Shape.__init__(self) 1014 | self.length = l 1015 | 1016 | def area(self): 1017 | return self.length*self.length 1018 | 1019 | aSquare= Square(3) 1020 | print aSquare.area() 1021 | 1022 | 1023 | 1024 | 1025 | 1026 | 1027 | 1028 | 1029 | #----------------------------------------# 1030 | 1031 | 1032 | Please raise a RuntimeError exception. 1033 | 1034 | Hints: 1035 | 1036 | Use raise() to raise an exception. 1037 | 1038 | Solution: 1039 | 1040 | raise RuntimeError('something wrong') 1041 | 1042 | 1043 | 1044 | #----------------------------------------# 1045 | Write a function to compute 5/0 and use try/except to catch the exceptions. 1046 | 1047 | Hints: 1048 | 1049 | Use try/except to catch exceptions. 1050 | 1051 | Solution: 1052 | 1053 | def throws(): 1054 | return 5/0 1055 | 1056 | try: 1057 | throws() 1058 | except ZeroDivisionError: 1059 | print "division by zero!" 1060 | except Exception, err: 1061 | print 'Caught an exception' 1062 | finally: 1063 | print 'In finally block for cleanup' 1064 | 1065 | 1066 | #----------------------------------------# 1067 | Define a custom exception class which takes a string message as attribute. 1068 | 1069 | Hints: 1070 | 1071 | To define a custom exception, we need to define a class inherited from Exception. 1072 | 1073 | Solution: 1074 | 1075 | class MyError(Exception): 1076 | """My own exception class 1077 | 1078 | Attributes: 1079 | msg -- explanation of the error 1080 | """ 1081 | 1082 | def __init__(self, msg): 1083 | self.msg = msg 1084 | 1085 | error = MyError("something wrong") 1086 | 1087 | #----------------------------------------# 1088 | Question: 1089 | 1090 | Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. 1091 | 1092 | Example: 1093 | If the following email address is given as input to the program: 1094 | 1095 | john@google.com 1096 | 1097 | Then, the output of the program should be: 1098 | 1099 | john 1100 | 1101 | In case of input data being supplied to the question, it should be assumed to be a console input. 1102 | 1103 | Hints: 1104 | 1105 | Use \w to match letters. 1106 | 1107 | Solution: 1108 | import re 1109 | emailAddress = raw_input() 1110 | pat2 = "(\w+)@((\w+\.)+(com))" 1111 | r2 = re.match(pat2,emailAddress) 1112 | print r2.group(1) 1113 | 1114 | 1115 | #----------------------------------------# 1116 | Question: 1117 | 1118 | Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. 1119 | 1120 | Example: 1121 | If the following email address is given as input to the program: 1122 | 1123 | john@google.com 1124 | 1125 | Then, the output of the program should be: 1126 | 1127 | google 1128 | 1129 | In case of input data being supplied to the question, it should be assumed to be a console input. 1130 | 1131 | Hints: 1132 | 1133 | Use \w to match letters. 1134 | 1135 | Solution: 1136 | import re 1137 | emailAddress = raw_input() 1138 | pat2 = "(\w+)@(\w+)\.(com)" 1139 | r2 = re.match(pat2,emailAddress) 1140 | print r2.group(2) 1141 | 1142 | 1143 | 1144 | 1145 | #----------------------------------------# 1146 | Question: 1147 | 1148 | Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. 1149 | 1150 | Example: 1151 | If the following words is given as input to the program: 1152 | 1153 | 2 cats and 3 dogs. 1154 | 1155 | Then, the output of the program should be: 1156 | 1157 | ['2', '3'] 1158 | 1159 | In case of input data being supplied to the question, it should be assumed to be a console input. 1160 | 1161 | Hints: 1162 | 1163 | Use re.findall() to find all substring using regex. 1164 | 1165 | Solution: 1166 | import re 1167 | s = raw_input() 1168 | print re.findall("\d+",s) 1169 | 1170 | 1171 | #----------------------------------------# 1172 | Question: 1173 | 1174 | 1175 | Print a unicode string "hello world". 1176 | 1177 | Hints: 1178 | 1179 | Use u'strings' format to define unicode string. 1180 | 1181 | Solution: 1182 | 1183 | unicodeString = u"hello world!" 1184 | print unicodeString 1185 | 1186 | #----------------------------------------# 1187 | Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. 1188 | 1189 | Hints: 1190 | 1191 | Use unicode() function to convert. 1192 | 1193 | Solution: 1194 | 1195 | s = raw_input() 1196 | u = unicode( s ,"utf-8") 1197 | print u 1198 | 1199 | #----------------------------------------# 1200 | Question: 1201 | 1202 | Write a special comment to indicate a Python source code file is in unicode. 1203 | 1204 | Hints: 1205 | 1206 | Solution: 1207 | 1208 | # -*- coding: utf-8 -*- 1209 | 1210 | #----------------------------------------# 1211 | Question: 1212 | 1213 | Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). 1214 | 1215 | Example: 1216 | If the following n is given as input to the program: 1217 | 1218 | 5 1219 | 1220 | Then, the output of the program should be: 1221 | 1222 | 3.55 1223 | 1224 | In case of input data being supplied to the question, it should be assumed to be a console input. 1225 | 1226 | Hints: 1227 | Use float() to convert an integer to a float 1228 | 1229 | Solution: 1230 | 1231 | n=int(raw_input()) 1232 | sum=0.0 1233 | for i in range(1,n+1): 1234 | sum += float(float(i)/(i+1)) 1235 | print sum 1236 | 1237 | 1238 | #----------------------------------------# 1239 | Question: 1240 | 1241 | Write a program to compute: 1242 | 1243 | f(n)=f(n-1)+100 when n>0 1244 | and f(0)=1 1245 | 1246 | with a given n input by console (n>0). 1247 | 1248 | Example: 1249 | If the following n is given as input to the program: 1250 | 1251 | 5 1252 | 1253 | Then, the output of the program should be: 1254 | 1255 | 500 1256 | 1257 | In case of input data being supplied to the question, it should be assumed to be a console input. 1258 | 1259 | Hints: 1260 | We can define recursive function in Python. 1261 | 1262 | Solution: 1263 | 1264 | def f(n): 1265 | if n==0: 1266 | return 0 1267 | else: 1268 | return f(n-1)+100 1269 | 1270 | n=int(raw_input()) 1271 | print f(n) 1272 | 1273 | #----------------------------------------# 1274 | 1275 | Question: 1276 | 1277 | 1278 | The Fibonacci Sequence is computed based on the following formula: 1279 | 1280 | 1281 | f(n)=0 if n=0 1282 | f(n)=1 if n=1 1283 | f(n)=f(n-1)+f(n-2) if n>1 1284 | 1285 | Please write a program to compute the value of f(n) with a given n input by console. 1286 | 1287 | Example: 1288 | If the following n is given as input to the program: 1289 | 1290 | 7 1291 | 1292 | Then, the output of the program should be: 1293 | 1294 | 13 1295 | 1296 | In case of input data being supplied to the question, it should be assumed to be a console input. 1297 | 1298 | Hints: 1299 | We can define recursive function in Python. 1300 | 1301 | 1302 | Solution: 1303 | 1304 | def f(n): 1305 | if n == 0: return 0 1306 | elif n == 1: return 1 1307 | else: return f(n-1)+f(n-2) 1308 | 1309 | n=int(raw_input()) 1310 | print f(n) 1311 | 1312 | 1313 | #----------------------------------------# 1314 | 1315 | #----------------------------------------# 1316 | 1317 | Question: 1318 | 1319 | The Fibonacci Sequence is computed based on the following formula: 1320 | 1321 | 1322 | f(n)=0 if n=0 1323 | f(n)=1 if n=1 1324 | f(n)=f(n-1)+f(n-2) if n>1 1325 | 1326 | Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. 1327 | 1328 | Example: 1329 | If the following n is given as input to the program: 1330 | 1331 | 7 1332 | 1333 | Then, the output of the program should be: 1334 | 1335 | 0,1,1,2,3,5,8,13 1336 | 1337 | 1338 | Hints: 1339 | We can define recursive function in Python. 1340 | Use list comprehension to generate a list from an existing list. 1341 | Use string.join() to join a list of strings. 1342 | 1343 | In case of input data being supplied to the question, it should be assumed to be a console input. 1344 | 1345 | Solution: 1346 | 1347 | def f(n): 1348 | if n == 0: return 0 1349 | elif n == 1: return 1 1350 | else: return f(n-1)+f(n-2) 1351 | 1352 | n=int(raw_input()) 1353 | values = [str(f(x)) for x in range(0, n+1)] 1354 | print ",".join(values) 1355 | 1356 | 1357 | #----------------------------------------# 1358 | 1359 | Question: 1360 | 1361 | Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console. 1362 | 1363 | Example: 1364 | If the following n is given as input to the program: 1365 | 1366 | 10 1367 | 1368 | Then, the output of the program should be: 1369 | 1370 | 0,2,4,6,8,10 1371 | 1372 | Hints: 1373 | Use yield to produce the next value in generator. 1374 | 1375 | In case of input data being supplied to the question, it should be assumed to be a console input. 1376 | 1377 | Solution: 1378 | 1379 | def EvenGenerator(n): 1380 | i=0 1381 | while i<=n: 1382 | if i%2==0: 1383 | yield i 1384 | i+=1 1385 | 1386 | 1387 | n=int(raw_input()) 1388 | values = [] 1389 | for i in EvenGenerator(n): 1390 | values.append(str(i)) 1391 | 1392 | print ",".join(values) 1393 | 1394 | 1395 | #----------------------------------------# 1396 | 1397 | Question: 1398 | 1399 | Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. 1400 | 1401 | Example: 1402 | If the following n is given as input to the program: 1403 | 1404 | 100 1405 | 1406 | Then, the output of the program should be: 1407 | 1408 | 0,35,70 1409 | 1410 | Hints: 1411 | Use yield to produce the next value in generator. 1412 | 1413 | In case of input data being supplied to the question, it should be assumed to be a console input. 1414 | 1415 | Solution: 1416 | 1417 | def NumGenerator(n): 1418 | for i in range(n+1): 1419 | if i%5==0 and i%7==0: 1420 | yield i 1421 | 1422 | n=int(raw_input()) 1423 | values = [] 1424 | for i in NumGenerator(n): 1425 | values.append(str(i)) 1426 | 1427 | print ",".join(values) 1428 | 1429 | 1430 | #----------------------------------------# 1431 | 1432 | Question: 1433 | 1434 | 1435 | Please write assert statements to verify that every number in the list [2,4,6,8] is even. 1436 | 1437 | 1438 | 1439 | Hints: 1440 | Use "assert expression" to make assertion. 1441 | 1442 | 1443 | Solution: 1444 | 1445 | li = [2,4,6,8] 1446 | for i in li: 1447 | assert i%2==0 1448 | 1449 | 1450 | #----------------------------------------# 1451 | Question: 1452 | 1453 | Please write a program which accepts basic mathematic expression from console and print the evaluation result. 1454 | 1455 | Example: 1456 | If the following string is given as input to the program: 1457 | 1458 | 35+3 1459 | 1460 | Then, the output of the program should be: 1461 | 1462 | 38 1463 | 1464 | Hints: 1465 | Use eval() to evaluate an expression. 1466 | 1467 | 1468 | Solution: 1469 | 1470 | expression = raw_input() 1471 | print eval(expression) 1472 | 1473 | 1474 | #----------------------------------------# 1475 | Question: 1476 | 1477 | Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. 1478 | 1479 | 1480 | Hints: 1481 | Use if/elif to deal with conditions. 1482 | 1483 | 1484 | Solution: 1485 | 1486 | import math 1487 | def bin_search(li, element): 1488 | bottom = 0 1489 | top = len(li)-1 1490 | index = -1 1491 | while top>=bottom and index==-1: 1492 | mid = int(math.floor((top+bottom)/2.0)) 1493 | if li[mid]==element: 1494 | index = mid 1495 | elif li[mid]>element: 1496 | top = mid-1 1497 | else: 1498 | bottom = mid+1 1499 | 1500 | return index 1501 | 1502 | li=[2,5,7,9,11,17,222] 1503 | print bin_search(li,11) 1504 | print bin_search(li,12) 1505 | 1506 | 1507 | 1508 | 1509 | #----------------------------------------# 1510 | Question: 1511 | 1512 | Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. 1513 | 1514 | 1515 | Hints: 1516 | Use if/elif to deal with conditions. 1517 | 1518 | 1519 | Solution: 1520 | 1521 | import math 1522 | def bin_search(li, element): 1523 | bottom = 0 1524 | top = len(li)-1 1525 | index = -1 1526 | while top>=bottom and index==-1: 1527 | mid = int(math.floor((top+bottom)/2.0)) 1528 | if li[mid]==element: 1529 | index = mid 1530 | elif li[mid]>element: 1531 | top = mid-1 1532 | else: 1533 | bottom = mid+1 1534 | 1535 | return index 1536 | 1537 | li=[2,5,7,9,11,17,222] 1538 | print bin_search(li,11) 1539 | print bin_search(li,12) 1540 | 1541 | 1542 | 1543 | 1544 | #----------------------------------------# 1545 | Question: 1546 | 1547 | Please generate a random float where the value is between 10 and 100 using Python math module. 1548 | 1549 | 1550 | 1551 | Hints: 1552 | Use random.random() to generate a random float in [0,1]. 1553 | 1554 | 1555 | Solution: 1556 | 1557 | import random 1558 | print random.random()*100 1559 | 1560 | #----------------------------------------# 1561 | Question: 1562 | 1563 | Please generate a random float where the value is between 5 and 95 using Python math module. 1564 | 1565 | 1566 | 1567 | Hints: 1568 | Use random.random() to generate a random float in [0,1]. 1569 | 1570 | 1571 | Solution: 1572 | 1573 | import random 1574 | print random.random()*100-5 1575 | 1576 | 1577 | #----------------------------------------# 1578 | Question: 1579 | 1580 | Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. 1581 | 1582 | 1583 | 1584 | Hints: 1585 | Use random.choice() to a random element from a list. 1586 | 1587 | 1588 | Solution: 1589 | 1590 | import random 1591 | print random.choice([i for i in range(11) if i%2==0]) 1592 | 1593 | 1594 | #----------------------------------------# 1595 | Question: 1596 | 1597 | Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension. 1598 | 1599 | 1600 | 1601 | Hints: 1602 | Use random.choice() to a random element from a list. 1603 | 1604 | 1605 | Solution: 1606 | 1607 | import random 1608 | print random.choice([i for i in range(201) if i%5==0 and i%7==0]) 1609 | 1610 | 1611 | 1612 | #----------------------------------------# 1613 | 1614 | Question: 1615 | 1616 | Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. 1617 | 1618 | 1619 | 1620 | Hints: 1621 | Use random.sample() to generate a list of random values. 1622 | 1623 | 1624 | Solution: 1625 | 1626 | import random 1627 | print random.sample(range(100), 5) 1628 | 1629 | #----------------------------------------# 1630 | Question: 1631 | 1632 | Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. 1633 | 1634 | 1635 | 1636 | Hints: 1637 | Use random.sample() to generate a list of random values. 1638 | 1639 | 1640 | Solution: 1641 | 1642 | import random 1643 | print random.sample([i for i in range(100,201) if i%2==0], 5) 1644 | 1645 | 1646 | #----------------------------------------# 1647 | Question: 1648 | 1649 | Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. 1650 | 1651 | 1652 | 1653 | Hints: 1654 | Use random.sample() to generate a list of random values. 1655 | 1656 | 1657 | Solution: 1658 | 1659 | import random 1660 | print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) 1661 | 1662 | #----------------------------------------# 1663 | 1664 | Question: 1665 | 1666 | Please write a program to randomly print a integer number between 7 and 15 inclusive. 1667 | 1668 | 1669 | 1670 | Hints: 1671 | Use random.randrange() to a random integer in a given range. 1672 | 1673 | 1674 | Solution: 1675 | 1676 | import random 1677 | print random.randrange(7,16) 1678 | 1679 | #----------------------------------------# 1680 | 1681 | Question: 1682 | 1683 | Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". 1684 | 1685 | 1686 | 1687 | Hints: 1688 | Use zlib.compress() and zlib.decompress() to compress and decompress a string. 1689 | 1690 | 1691 | Solution: 1692 | 1693 | import zlib 1694 | s = 'hello world!hello world!hello world!hello world!' 1695 | t = zlib.compress(s) 1696 | print t 1697 | print zlib.decompress(t) 1698 | 1699 | #----------------------------------------# 1700 | Question: 1701 | 1702 | Please write a program to print the running time of execution of "1+1" for 100 times. 1703 | 1704 | 1705 | 1706 | Hints: 1707 | Use timeit() function to measure the running time. 1708 | 1709 | Solution: 1710 | 1711 | from timeit import Timer 1712 | t = Timer("for i in range(100):1+1") 1713 | print t.timeit() 1714 | 1715 | #----------------------------------------# 1716 | Question: 1717 | 1718 | Please write a program to shuffle and print the list [3,6,7,8]. 1719 | 1720 | 1721 | 1722 | Hints: 1723 | Use shuffle() function to shuffle a list. 1724 | 1725 | Solution: 1726 | 1727 | from random import shuffle 1728 | li = [3,6,7,8] 1729 | shuffle(li) 1730 | print li 1731 | 1732 | #----------------------------------------# 1733 | Question: 1734 | 1735 | Please write a program to shuffle and print the list [3,6,7,8]. 1736 | 1737 | 1738 | 1739 | Hints: 1740 | Use shuffle() function to shuffle a list. 1741 | 1742 | Solution: 1743 | 1744 | from random import shuffle 1745 | li = [3,6,7,8] 1746 | shuffle(li) 1747 | print li 1748 | 1749 | 1750 | 1751 | #----------------------------------------# 1752 | Question: 1753 | 1754 | Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. 1755 | 1756 | Hints: 1757 | Use list[index] notation to get a element from a list. 1758 | 1759 | Solution: 1760 | 1761 | subjects=["I", "You"] 1762 | verbs=["Play", "Love"] 1763 | objects=["Hockey","Football"] 1764 | for i in range(len(subjects)): 1765 | for j in range(len(verbs)): 1766 | for k in range(len(objects)): 1767 | sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) 1768 | print sentence 1769 | 1770 | 1771 | #----------------------------------------# 1772 | Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. 1773 | 1774 | Hints: 1775 | Use list comprehension to delete a bunch of element from a list. 1776 | 1777 | Solution: 1778 | 1779 | li = [5,6,77,45,22,12,24] 1780 | li = [x for x in li if x%2!=0] 1781 | print li 1782 | 1783 | #----------------------------------------# 1784 | Question: 1785 | 1786 | By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. 1787 | 1788 | Hints: 1789 | Use list comprehension to delete a bunch of element from a list. 1790 | 1791 | Solution: 1792 | 1793 | li = [12,24,35,70,88,120,155] 1794 | li = [x for x in li if x%5!=0 and x%7!=0] 1795 | print li 1796 | 1797 | 1798 | #----------------------------------------# 1799 | Question: 1800 | 1801 | By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. 1802 | 1803 | Hints: 1804 | Use list comprehension to delete a bunch of element from a list. 1805 | Use enumerate() to get (index, value) tuple. 1806 | 1807 | Solution: 1808 | 1809 | li = [12,24,35,70,88,120,155] 1810 | li = [x for (i,x) in enumerate(li) if i%2!=0] 1811 | print li 1812 | 1813 | #----------------------------------------# 1814 | 1815 | Question: 1816 | 1817 | By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0. 1818 | 1819 | Hints: 1820 | Use list comprehension to make an array. 1821 | 1822 | Solution: 1823 | 1824 | array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] 1825 | print array 1826 | 1827 | #----------------------------------------# 1828 | Question: 1829 | 1830 | By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. 1831 | 1832 | Hints: 1833 | Use list comprehension to delete a bunch of element from a list. 1834 | Use enumerate() to get (index, value) tuple. 1835 | 1836 | Solution: 1837 | 1838 | li = [12,24,35,70,88,120,155] 1839 | li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] 1840 | print li 1841 | 1842 | 1843 | 1844 | #----------------------------------------# 1845 | 1846 | Question: 1847 | 1848 | By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. 1849 | 1850 | Hints: 1851 | Use list's remove method to delete a value. 1852 | 1853 | Solution: 1854 | 1855 | li = [12,24,35,24,88,120,155] 1856 | li = [x for x in li if x!=24] 1857 | print li 1858 | 1859 | 1860 | #----------------------------------------# 1861 | Question: 1862 | 1863 | With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. 1864 | 1865 | Hints: 1866 | Use set() and "&=" to do set intersection operation. 1867 | 1868 | Solution: 1869 | 1870 | set1=set([1,3,6,78,35,55]) 1871 | set2=set([12,24,35,24,88,120,155]) 1872 | set1 &= set2 1873 | li=list(set1) 1874 | print li 1875 | 1876 | #----------------------------------------# 1877 | 1878 | With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. 1879 | 1880 | Hints: 1881 | Use set() to store a number of values without duplicate. 1882 | 1883 | Solution: 1884 | 1885 | def removeDuplicate( li ): 1886 | newli=[] 1887 | seen = set() 1888 | for item in li: 1889 | if item not in seen: 1890 | seen.add( item ) 1891 | newli.append(item) 1892 | 1893 | return newli 1894 | 1895 | li=[12,24,35,24,88,120,155,88,120,155] 1896 | print removeDuplicate(li) 1897 | 1898 | 1899 | #----------------------------------------# 1900 | Question: 1901 | 1902 | Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. 1903 | 1904 | Hints: 1905 | Use Subclass(Parentclass) to define a child class. 1906 | 1907 | Solution: 1908 | 1909 | class Person(object): 1910 | def getGender( self ): 1911 | return "Unknown" 1912 | 1913 | class Male( Person ): 1914 | def getGender( self ): 1915 | return "Male" 1916 | 1917 | class Female( Person ): 1918 | def getGender( self ): 1919 | return "Female" 1920 | 1921 | aMale = Male() 1922 | aFemale= Female() 1923 | print aMale.getGender() 1924 | print aFemale.getGender() 1925 | 1926 | 1927 | 1928 | #----------------------------------------# 1929 | Question: 1930 | 1931 | Please write a program which count and print the numbers of each character in a string input by console. 1932 | 1933 | Example: 1934 | If the following string is given as input to the program: 1935 | 1936 | abcdefgabc 1937 | 1938 | Then, the output of the program should be: 1939 | 1940 | a,2 1941 | c,2 1942 | b,2 1943 | e,1 1944 | d,1 1945 | g,1 1946 | f,1 1947 | 1948 | Hints: 1949 | Use dict to store key/value pairs. 1950 | Use dict.get() method to lookup a key with default value. 1951 | 1952 | Solution: 1953 | 1954 | dic = {} 1955 | s=raw_input() 1956 | for s in s: 1957 | dic[s] = dic.get(s,0)+1 1958 | print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) 1959 | 1960 | #----------------------------------------# 1961 | 1962 | Question: 1963 | 1964 | Please write a program which accepts a string from console and print it in reverse order. 1965 | 1966 | Example: 1967 | If the following string is given as input to the program: 1968 | 1969 | rise to vote sir 1970 | 1971 | Then, the output of the program should be: 1972 | 1973 | ris etov ot esir 1974 | 1975 | Hints: 1976 | Use list[::-1] to iterate a list in a reverse order. 1977 | 1978 | Solution: 1979 | 1980 | s=raw_input() 1981 | s = s[::-1] 1982 | print s 1983 | 1984 | #----------------------------------------# 1985 | 1986 | Question: 1987 | 1988 | Please write a program which accepts a string from console and print the characters that have even indexes. 1989 | 1990 | Example: 1991 | If the following string is given as input to the program: 1992 | 1993 | H1e2l3l4o5w6o7r8l9d 1994 | 1995 | Then, the output of the program should be: 1996 | 1997 | Helloworld 1998 | 1999 | Hints: 2000 | Use list[::2] to iterate a list by step 2. 2001 | 2002 | Solution: 2003 | 2004 | s=raw_input() 2005 | s = s[::2] 2006 | print s 2007 | #----------------------------------------# 2008 | 2009 | 2010 | Question: 2011 | 2012 | Please write a program which prints all permutations of [1,2,3] 2013 | 2014 | 2015 | Hints: 2016 | Use itertools.permutations() to get permutations of list. 2017 | 2018 | Solution: 2019 | 2020 | import itertools 2021 | print list(itertools.permutations([1,2,3])) 2022 | 2023 | #----------------------------------------# 2024 | Question: 2025 | 2026 | Write a program to solve a classic ancient Chinese puzzle: 2027 | We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? 2028 | 2029 | Hint: 2030 | Use for loop to iterate all possible solutions. 2031 | 2032 | Solution: 2033 | 2034 | def solve(numheads,numlegs): 2035 | ns='No solutions!' 2036 | for i in range(numheads+1): 2037 | j=numheads-i 2038 | if 2*i+4*j==numlegs: 2039 | return i,j 2040 | return ns,ns 2041 | 2042 | numheads=35 2043 | numlegs=94 2044 | solutions=solve(numheads,numlegs) 2045 | print solutions 2046 | 2047 | #----------------------------------------# 2048 | 2049 | 2050 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/cblte/100-golang-exercises 2 | 3 | go 1.16 4 | --------------------------------------------------------------------------------