Practice questions on Go for and for

Level 1

Print all elements of a list using for loop.
a = [1,2,3,4,5]
for i in a:
  print i

Take inputs from user to make a list. Again take one input from user and search it in the list and delete that element, if found. Iterate over list using for loop.

Print multiplication table of 14 from a list in which multiplication table of 12 is stored.
This type of example is given in tutorial

You are given with a list of integer elements. Make a new list which will store square of elements of previous list.
for i in a:

Using range(1,101), make two list, one containing all even numbers and other containing all odd numbers.
for i in range(1,101):
  if i%2 == 0:

From the two list obtained in previous question, make new lists, containing only numbers which are divisible by 4, 6, 8, 10, 3, 5, 7 and 9 in separate lists.
for i in even:
  if i%4 == 0:
  if i%6 == 0:

From a list containing ints, strings and floats, make three lists to store them separately.

Level 2

Using range(1,101), make a list containing only prime numbers.
You can use sieve algorithm to find prime number and it is more efficent. See this answer
#Check for prime number
#is the the number to be checked for
  j = 2
  count = 0
  while j <= i:
    if i%j == 0:
      count = count+1
    j = j+1
  #if count > 1 then it is not prime

Initialize a 2D list of 3*3 matrix. E.g.-
1 2 3
4 5 6
7 8 9

Check if the matrix is symmetric or not.
a = [[1,2,3],[2,4,5],[3,5,6]]
sym = True
for i in range(0,3):
  for j in range(0,3):
    if a[i][j]!=a[j][i]:
      sym = False
print sym

Sorting refers to arranging data in a particular format. Sort a list of integers in ascending order ( without using built-in sorted function ). One of the algorithm is selection sort. Use below explanation of selection sort to do this.
2 3 1 45 15
First iteration : Compare every element after first element with first element and if it is larger then swap. In first iteration, 2 is larger than 1. So, swap it.
1 3 2 45 15
Second iteration : Compare every element after second element with second element and if it is larger then swap. In second iteration, 3 is larger than 2. So, swap it.
1 2 3 45 15
Third iteration : Nothing will swap as 3 is smaller than every element after it.
1 2 3 45 15
Fourth iteration : Compare every element after fourth element with fourth element and if it is larger then swap. In fourth iteration, 45 is larger than 15. So, swap it.
1 2 3 15 45
a = [2,3,1,45,15]
for i in range(0,len(a)):
  for j in range(i+1,len(a)):
    if a[i]>a[j]:
      a[i],a[j] = a[j],a[i]
print a

Level 3

Ask Yours
Post Yours