add: appending quiz and exercises

...
This commit is contained in:
Inanc Gumus 2019-01-28 15:49:49 +03:00
parent 0aab0d17e9
commit e34bb6f526
28 changed files with 658 additions and 136 deletions

View File

@ -0,0 +1,25 @@
package main
// ---------------------------------------------------------
// EXERCISE: Append
//
// Please follow the instructions within the code below.
//
// EXPECTED OUTPUT
// They are equal.
//
// HINTS
// bytes.Equal function allows you to compare two byte
// slices easily. Check its documentation: go doc bytes.Equal
// ---------------------------------------------------------
func main() {
// 1. uncomment the code below
// png, header := []byte{'P', 'N', 'G'}, []byte{}
// 2. append elements to header to make it equal with the png slice
// 3. compare the slices using the bytes.Equal function
// 4. print whether they're equal or not
}

View File

@ -0,0 +1,23 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"bytes"
"fmt"
)
func main() {
png, header := []byte{'P', 'N', 'G'}, []byte{}
header = append(header, png...)
if bytes.Equal(png, header) {
fmt.Println("They are equal")
}
}

View File

@ -0,0 +1,41 @@
package main
// ---------------------------------------------------------
// EXERCISE: Append #2
//
// 1. Create the following nil slices:
// + Pizza toppings
// + Departure times
// + Student graduation years
// + On/off states of lights in a room
//
// 2. Append them some elements (use your creativity!)
//
// 3. Print all the slices
//
//
// EXPECTED OUTPUT
// (Your output may change, mine is like so:)
//
// pizza : [pepperoni onions extra cheese]
//
// graduations : [1998 2005 2018]
//
// departures : [2019-01-28 15:09:31.294594 +0300 +03 m=+0.000325020
// 2019-01-29 15:09:31.294594 +0300 +03 m=+86400.000325020
// 2019-01-30 15:09:31.294594 +0300 +03 m=+172800.000325020]
//
// lights : [true false true]
//
//
// HINTS
// + For departure times, use the time.Time type. Check its documentation.
//
// now := time.Now() -> Gives you the current time
// now.Add(time.Hour*24) -> Gives you a time.Time 24 hours after `now`
//
// + For graduation years, you can use the int type
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,55 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"time"
)
func main() {
// ------------------------------------------------------------
// Create nil slices
// ------------------------------------------------------------
// Pizza toppings
var pizza []string
// Departure times
var departures []time.Time
// Student graduation years
var grads []int
// On/off states of lights in a room
var lights []bool
// ------------------------------------------------------------
// Append them some elements (use your creativity!)
// ------------------------------------------------------------
pizza = append(pizza, "pepperoni", "onions", "extra cheese")
now := time.Now()
departures = append(departures,
now,
now.Add(time.Hour*24), // 24 hours after `now`
now.Add(time.Hour*48)) // 48 hours after `now`
grads = append(grads, 1998, 2005, 2018)
lights = append(lights, true, false, true)
// ------------------------------------------------------------
// Print the slices
// ------------------------------------------------------------
fmt.Printf("pizza : %s\n", pizza)
fmt.Printf("\ngraduations : %d\n", grads)
fmt.Printf("\ndepartures : %s\n", departures)
fmt.Printf("\nlights : %t\n", lights)
}

View File

@ -0,0 +1,27 @@
package main
// ---------------------------------------------------------
// EXERCISE: Append #3 — Fix the problems
//
// Fix the problems in the code below.
//
// BONUS
//
// Simplify the code.
//
// EXPECTED OUTPUT
//
// toppings: [black olives green peppers onions extra cheese]
//
// ---------------------------------------------------------
func main() {
// toppings := []int{"black olives", "green peppers"}
// var pizza [3]string
// append(pizza, ...toppings)
// pizza = append(toppings, "onions")
// toppings = append(pizza, extra cheese)
// fmt.Printf("pizza : %s\n", pizza)
}

View File

@ -0,0 +1,20 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
func main() {
toppings := []string{"black olives", "green peppers"}
var pizza []string
pizza = append(pizza, toppings...)
pizza = append(pizza, "onions", "extra cheese")
fmt.Printf("toppings: %s\n", pizza)
}

View File

@ -0,0 +1,42 @@
package main
// ---------------------------------------------------------
// EXERCISE: Append #4 — Sort to a file
//
// 1. Get arguments from command-line
//
// 2. Sort them
//
// 3. Write the sorted slice to a file
//
//
// EXPECTED OUTPUT
//
// go run main.go
// Send me some items and I will sort them
//
// go run main.go orange banana apple
//
// cat sorted.txt
// apple
// banana
// orange
//
//
// HINTS
//
// ONLY READ THIS IF YOU GET STUCK
//
// Below, []string means string slice, []byte means byte slice.
//
// + You can use the os.Args[1:] to get a []string
// + Then you can sort it using sort.Strings
// + Use ioutil.WriteFile to write to a file.
// + But you need to convert []string to []byte to be able to
// write it to a file using the ioutil.WriteFile.
// + To do that, create a new []byte and append the elements of your
// []string.
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,37 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"io/ioutil"
"os"
"sort"
)
func main() {
items := os.Args[1:]
if len(items) == 0 {
fmt.Println("Send me some items and I will sort them")
return
}
sort.Strings(items)
var data []byte
for _, s := range items {
data = append(data, s...)
data = append(data, '\n')
}
err := ioutil.WriteFile("sorted.txt", data, 0644)
if err != nil {
fmt.Println(err)
return
}
}

View File

@ -0,0 +1,70 @@
package main
import (
"fmt"
"io/ioutil"
"os"
"sort"
)
// ---------------------------------------------------------
// EXERCISE: Append #5 — Sort to a file with ordinals
//
// Use the previous exercise: Append #4
//
// This time, print the sorted items with ordinals
// (see the expected output)
//
//
// EXPECTED OUTPUT
//
// go run main.go
// Send me some items and I will sort them
//
// go run main.go orange banana apple
//
// cat sorted.txt
// 1. apple
// 2. banana
// 3. orange
//
//
// HINTS
//
// ONLY READ THIS IF YOU GET STUCK
//
// + You can use strconv.AppendInt function to append an int
// to a byte slice. strconv contains a lot of functions for appending
// other basic types as well.
//
// + You can append individual characters to a byte slice using
// rune literals:
//
// var slice []byte
// slice = append(slice, 'h', 'i', ' ', '!')
// fmt.Printf("%s\n", slice)
//
// Above code prints: hi !
// ---------------------------------------------------------
func main() {
items := os.Args[1:]
if len(items) == 0 {
fmt.Println("Send me some items and I will sort them")
return
}
sort.Strings(items)
var data []byte
for _, s := range items {
data = append(data, s...)
data = append(data, '\n')
}
err := ioutil.WriteFile("sorted.txt", data, 0644)
if err != nil {
fmt.Println(err)
return
}
}

View File

@ -0,0 +1,40 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"io/ioutil"
"os"
"sort"
"strconv"
)
func main() {
items := os.Args[1:]
if len(items) == 0 {
fmt.Println("Send me some items and I will sort them")
return
}
sort.Strings(items)
var data []byte
for i, s := range items {
data = strconv.AppendInt(data, int64(i+1), 10)
data = append(data, '.', ' ')
data = append(data, s...)
data = append(data, '\n')
}
err := ioutil.WriteFile("sorted.txt", data, 0644)
if err != nil {
fmt.Println(err)
return
}
}

View File

@ -0,0 +1,56 @@
package main
// ---------------------------------------------------------
// EXERCISE: Append #6 — Print the directories
//
// Create a program that can get multiple directory paths from
// the command-line, and prints only their subdirectories into a
// file named: dirs.txt
//
//
// 1. Get the directory paths from command-line
//
// 2. Append the names of subdirectories inside each directory
// to a byte slice
//
// 3. Write that byte slice to dirs.txt file
//
//
// EXPECTED OUTPUT
//
// go run main.go
// Please provide directory paths
//
// go run main.go dir/ dir2/
//
// cat dirs.txt
//
// dir/
// subdir1/
// subdir2/
//
// dir2/
// subdir1/
// subdir2/
// subdir3/
//
//
// HINTS
//
// ONLY READ THIS IF YOU GET STUCK
//
// + Get all the files in a directory using ioutil.ReadDir
// (A directory is also a file)
//
// + You can use IsDir method of a FileInfo value to detect
// whether a file is a directory or not: go doc os.FileInfo.IsDir
//
// + You can use '\t' escape sequence for indenting the subdirs.
//
// + You can find a sample directory structure under:
// solution/ directory
//
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,4 @@
*
!subdir1
!subdir2
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,5 @@
*
!subdir1
!subdir2
!subdir3
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,9 @@
dir/
subdir1/
subdir2/
dir2/
subdir1/
subdir2/
subdir3/

View File

@ -0,0 +1,51 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
paths := os.Args[1:]
if len(paths) == 0 {
fmt.Println("Please provide directory paths")
return
}
var dirs []byte
for _, dir := range paths {
files, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Println(err)
return
}
dirs = append(dirs, dir...)
dirs = append(dirs, '\n')
for _, file := range files {
if file.IsDir() {
dirs = append(dirs, '\t')
dirs = append(dirs, file.Name()...)
dirs = append(dirs, '/', '\n')
}
}
dirs = append(dirs, '\n')
}
err := ioutil.WriteFile("dirs.txt", dirs, 0644)
if err != nil {
fmt.Println(err)
return
}
}

View File

@ -12,4 +12,20 @@
5. **[Fix the Problems](https://github.com/inancgumus/learngo/tree/master/15-slices/exercises/05-fix-the-problems)**
6. **[Compare the slices](https://github.com/inancgumus/learngo/tree/master/15-slices/exercises/06-compare-the-slices)**
6. **[Compare the slices](https://github.com/inancgumus/learngo/tree/master/15-slices/exercises/06-compare-the-slices)**
---
## Exercises Level II - Appending
1. **[Append #1 — Append and compare byte slices](https://github.com/inancgumus/learngo/tree/master/15-slices/exercises/07-append)**
2. **[Append #2 — Append to a nil slice](https://github.com/inancgumus/learngo/tree/master/15-slices/exercises/08-append-2)**
3. **[Append #3 — Fix the problems](https://github.com/inancgumus/learngo/tree/master/15-slices/exercises/09-append-3-fix)**
4. **[Append #4 — Sort and write items to a file](https://github.com/inancgumus/learngo/tree/master/15-slices/exercises/10-append-4-sort-to-a-file)**
5. **[Append #5 — Sort and write items to a file with their ordinals](https://github.com/inancgumus/learngo/tree/master/15-slices/exercises/11-append-5-sort-to-a-file)**
5. **[Append #6 — Find and write the names of subdirectories to a file](https://github.com/inancgumus/learngo/tree/master/15-slices/exercises/12-append-6-print-directories)**

View File

@ -0,0 +1,66 @@
# Appending Quiz
## How does the append function work?
1. It appends new elements to the given slice on the fly and returns a new slice, normally, it doesn't change the given slice *CORRECT*
2. It appends new elements to the given slice and returns the existing slice
3. It appends new elements to the given slice and returns a new slice, it also changes the given slice
> **1:** Yes, the append function doesn't change the given slice unless you overwrite the result of the append function back to the original slice. Most of the times, this is true.
>
> **2:** It doesn't return the existing slice, it returns a new slice. That's why you usually save the result of the append back to the original slice.
>
> **3:** It doesn't change the given slice, it creates and returns a new slice. Most of the times, this is true.
## When you call the append function, where does it append the new elements?
1. It appends them at the beginning of the given slice
2. It appends them at the middle of the given slice
3. It appends them after the length of the given slice *CORRECT*
> **3:** Yes! The append function appends the new elements by looking at the length of the given slice and then returns a new slice with the newly appended elements.
## What's the problem with the following code?
```go
nums := []int{9, 7, 5}
append(nums, []int{2, 4, 6}...)
fmt.Println(nums[3])
```
1. It can't append to an int slice
2. It can't append a slice to another slice
3. It tries to get an element that doesn't exist yet *CORRECT*
> **3:** That's right. The append function returns a new slice with the newly added elements. But here, the code doesn't save the result of the append, so the nums slice only has 3 elements. So, `nums[3]` is invalid, because there are only 3 elements in the nums slice.
## What does this program print?
```go
nums := []int{9, 7, 5}
evens := append(nums, []int{2, 4, 6}...)
fmt.Println(nums, evens)
```
1. [9 7 5] [2 4 6]
2. [9 7 5] [9 7 5 2 4 6] *CORRECT*
3. [9 7 5 2 4 6] [2 4 6]
4. [9 7 5 2 4 6] [9 7 5 2 4 6]
> **2:** It appends the new elements to the nums slice but it saves the returned slice to the evens slice. So, the nums slice doesn't change. That's why, it prints the original elements from the nums slice first, then it prints the evens slice with the newly added elements.
>
> **3, 4:** It doesn't save the result of the append call back into the nums slice, so the nums slice doesn't contain the new elements.
## What does this program print?
```go
nums := []int{9, 7, 5}
nums = append(nums, 2, 4, 6)
fmt.Println(nums)
```
1. [9 7 5 2 4 6] *CORRECT*
2. [9 7 5]
3. [2 4 6]
4. [2 4 6 9 7 5]
> **1:** It overwrites the nums slice with the new slice that is returned from the append function. So the nums slice has got the newly appended elements.

View File

@ -1,3 +1,5 @@
# Slice Quizzes
* [Slices vs Arrays](1-slices-vs-arrays.md)
* [Slices vs Arrays](1-slices-vs-arrays.md)
* [Appending](2-appending.md)

View File

@ -1,17 +1,6 @@
# Slice Exercises
## TODO
* append to slices
* append to a nil slice
* append to an empty slice
* check their length — see how they grow
* fix the problem (forgetten overwriting to the same slice)
* get arguments from command line and make them uppercase
* multiply the numbers
* slicing
* slice exercises... n:m.. using len etc..
* create a pagination

View File

@ -1,123 +0,0 @@
# Slice Basics Quiz
## How does the append function work?
1. It appends new elements to the given slice and returns a new slice, it doesn't change the given slice *CORRECT*
2. It appends new elements to the given slice and returns the existing slice
3. It appends new elements to the given slice and returns a new slice, it also changes the given slice
> **1:** Yes, the append function doesn't change the given slice unless you overwrite the result of the append function back to the original slice.
>
> **2:** It doesn't return the existing slice, it returns a new slice. That's why you usually save the result of the append back to the original slice.
>
> **3:** It doesn't change the given slice, it creates and returns a new slice.
## When you call the append function, where it does appends the new elements?
1. It appends them at the beginning of the given slice
2. It appends them at the middle of the given slice
3. It appends them after the length of the given slice *CORRECT*
> **3:** Yes! The append function appends the new elements by looking at the length of the given slice and then returns a new slice with the newly appended elements.
## What's the problem with the following code?
```go
nums := []int{9, 7, 5}
append(nums, []int{2, 4, 6}...)
fmt.Println(nums[3])
```
1. It can't append to an int slice
2. It can't append a slice to another slice
3. It gets an element that doesn't exist yet *CORRECT*
> **3:** That's right. The append function returns a new slice with the newly added elements. But here, it doesn't save the result of the append, so the nums slice only has 3 elements. So, `nums[3]` is invalid, it doesn't exist.
## What does this program print?
```go
nums := []int{9, 7, 5}
evens := append(nums, []int{2, 4, 6}...)
fmt.Println(nums, evens)
```
1. [9 7 5] [2 4 6]
2. [9 7 5] [9 7 5 2 4 6] *CORRECT*
3. [9 7 5 2 4 6] [2 4 6]
4. [9 7 5 2 4 6] [9 7 5 2 4 6]
> **2:** It appends the new elements to the nums slice but it saves the returned slice to the evens slice. So, the nums slice doesn't change. That's why, it prints the original elements from the nums slice first, then it prints the evens slice with the newly added elements.
>
> **3, 4:** It doesn't save the result of the append call back into the nums slice, so the nums slice doesn't contain the new elements.
## What does this program print?
```go
nums := []int{9, 7, 5}
nums = append(nums, 2, 4, 6)
fmt.Println(nums)
```
1. [9 7 5 2 4 6] *CORRECT*
2. [9 7 5]
3. [2 4 6]
4. [2 4 6 9 7 5]
> **1:** It overwrites the nums slice with the new slice that is returned from the append function. So the nums slice has the newly appended elements.
## What does this program print?
```go
nums := []int{9, 7, 5}
nums = append(nums, 2, 4, 6)
fmt.Println(nums[2:4])
```
1. [9 7 5 2 4 6]
2. [5 2] *CORRECT*
3. [4 6]
4. [7 2]
> **2:** nums is [9 7 5 2 4 6]. So, nums[2:4] is [5 2]. Remember, in nums[2:4] -> 2 is the starting index, so nums[2] is 5; And 4 is the stopping position, so nums[4-1] is 2 (-1 because the stopping position is the element position not an index). So, nums[2:4] returns a new slice that contains the elements at the middle of the nums slice.
## What does this program print?
```go
names := []string{"einstein", "rosen", "newton"}
fmt.Println(names[:])
```
1. [einstein rosen newton] *CORRECT*
2. [einstein rosen]
3. [einstein]
4. []
> **1:** The start index's default value is 0, and the stop position's default value is the length of the slice. So, `names[:]` equals to `names[0:3]`. It returns a new slice with the same elements.
## How can you get "rosen" element?
```go
names := []string{"einstein", "rosen", "newton"}
names2 := names[1:len(names) - 1]
```
1. names2[0] *CORRECT*
2. names2[1]
3. names2[2]
> **1:** That's right: names2 is ["rosen"] after the slicing.
>
> **2:** That's not right. names is ["einstein" "rosen" "newton"] but names2 is ["rosen"] after the slicing. So, names2[1] is an error, it's because, the length of the names2 is 1.
## What does this program print?
```go
names := []string{"einstein", "rosen", "newton"}
names = names[1:]
names = names[1:]
fmt.Println(names)
```
1. [einstein rosen newton]
2. [rosen newton]
3. [newton] *CORRECT*
4. []
> **3:** Remember, slicing returns a new slice. Here, each slicing statement overwrites the names slice with the newly returned slice from the slicing. At first, the names was [einstein rosen newton. After the first slicing, the names becomes [rosen newton]. After the second slicing, names becomes [newton]. See this for the complete explanation: https://play.golang.org/p/EsEHrSeByFR

View File

@ -0,0 +1,57 @@
# Slicing Quiz
## What does this program print?
```go
nums := []int{9, 7, 5}
nums = append(nums, 2, 4, 6)
fmt.Println(nums[2:4])
```
1. [9 7 5 2 4 6]
2. [5 2] *CORRECT*
3. [4 6]
4. [7 2]
> **2:** nums is [9 7 5 2 4 6]. So, nums[2:4] is [5 2]. Remember, in nums[2:4] -> 2 is the starting index, so nums[2] is 5; And 4 is the stopping position, so nums[4-1] is 2 (-1 because the stopping position is the element position not an index). So, nums[2:4] returns a new slice that contains the elements at the middle of the nums slice.
## What does this program print?
```go
names := []string{"einstein", "rosen", "newton"}
fmt.Println(names[:])
```
1. [einstein rosen newton] *CORRECT*
2. [einstein rosen]
3. [einstein]
4. []
> **1:** The start index's default value is 0, and the stop position's default value is the length of the slice. So, `names[:]` equals to `names[0:3]`. It returns a new slice with the same elements.
## How can you get "rosen" element?
```go
names := []string{"einstein", "rosen", "newton"}
names2 := names[1:len(names) - 1]
```
1. names2[0] *CORRECT*
2. names2[1]
3. names2[2]
> **1:** That's right: names2 is ["rosen"] after the slicing.
>
> **2:** That's not right. names is ["einstein" "rosen" "newton"] but names2 is ["rosen"] after the slicing. So, names2[1] is an error, it's because, the length of the names2 is 1.
## What does this program print?
```go
names := []string{"einstein", "rosen", "newton"}
names = names[1:]
names = names[1:]
fmt.Println(names)
```
1. [einstein rosen newton]
2. [rosen newton]
3. [newton] *CORRECT*
4. []
> **3:** Remember, slicing returns a new slice. Here, each slicing statement overwrites the names slice with the newly returned slice from the slicing. At first, the names was [einstein rosen newton. After the first slicing, the names becomes [rosen newton]. After the second slicing, names becomes [newton]. See this for the complete explanation: https://play.golang.org/p/EsEHrSeByFR