Skip to content
wannacode

Tasks

All the tasks of the course in one place. First 50 standalone tasks from "Hello, World" to the shortest path in a grid, each with an example and a solution in Python checked with a real compiler. Then the tasks from the lessons, by module: each one leads to the lesson that explains what you need.

50 tasks to practise

  1. 1. Hello World

    Print the text Hello, World! to the console; the program takes no input.

    No input.

    Output
    Hello, World!

    What you need is in the lesson: Your first program

    Solution
    print("Hello, World!")
  2. 2. Greet the user

    Read a name from one line and greet the person by name as "Hello, <name>!".

    Input
    Maria
    Output
    Hello, Maria!

    What you need is in the lesson: Input and output

    Solution
    name = input()
    print("Hello, " + name + "!")
  3. 3. Print the age

    Read the user's age (a whole number), store it in a variable and print it in a sentence.

    Input
    17
    Output
    You are 17 years old.

    What you need is in the lesson: Variables and types

    Solution
    age = int(input())
    print("You are " + str(age) + " years old.")
  4. 4. Unit converter

    Read a length in inches (it may be a decimal) and convert it to centimetres: 1 inch = 2.54 cm. Print the result with 2 decimal places.

    Input
    12.5
    Output
    31.75 cm

    What you need is in the lesson: Operators and arithmetic

    Solution
    inches = float(input())
    print(f"{inches * 2.54:.2f} cm")
  5. 5. Even or odd

    Read a whole number and print whether it is even or odd.

    Input
    7
    Output
    7 is odd.

    What you need is in the lesson: Conditions

    Solution
    number = int(input())
    if number % 2 == 0:
    print(str(number) + " is even.")
    else:
    print(str(number) + " is odd.")
  6. 6. Sum of two numbers

    Read two whole numbers, each on its own line, and print their sum.

    Input
    12
    30
    Output
    The sum is 42.

    What you need is in the lesson: Operators and arithmetic

    Solution
    first = int(input())
    second = int(input())
    print("The sum is " + str(first + second) + ".")
  7. 7. Area of a square

    Read the side of a square (a whole number) and print its area.

    Input
    5
    Output
    The area is 25.

    What you need is in the lesson: Operators and arithmetic

    Solution
    side = int(input())
    print("The area is " + str(side * side) + ".")
  8. 8. Volume of a sphere

    Read the radius r (it may be a decimal) and print the volume of the sphere V = 4/3 · π · r³ with 2 decimal places.

    Input
    3
    Output
    The volume is 113.10.

    What you need is in the lesson: Operators and arithmetic

    Solution
    import math
    r = float(input())
    volume = 4 / 3 * math.pi * r ** 3
    print(f"The volume is {volume:.2f}.")
  9. 9. Compare two numbers

    Read two whole numbers, each on its own line, and print the larger one (if they are equal, either will do).

    Input
    8
    15
    Output
    The larger one is 15.

    What you need is in the lesson: Conditions

    Solution
    a = int(input())
    b = int(input())
    if a > b:
    print("The larger one is " + str(a) + ".")
    else:
    print("The larger one is " + str(b) + ".")
  10. 10. Triangle check

    Read three whole numbers, each on its own line, and check whether they can be the sides of a triangle: any two of them must add up to more than the third.

    Input
    3
    4
    5
    Output
    They can form a triangle.

    What you need is in the lesson: Conditions

    Solution
    a = int(input())
    b = int(input())
    c = int(input())
    if a + b > c and a + c > b and b + c > a:
    print("They can form a triangle.")
    else:
    print("They cannot form a triangle.")
  11. 11. Grade to words

    Read a mark on the Bulgarian scale from 2 to 6 (it may be a decimal) and print it in words: 5.50 and up is Excellent, 4.50 and up Very good, 3.50 and up Good, 3.00 and up Average, below 3.00 Poor.

    Input
    4.75
    Output
    Very good

    What you need is in the lesson: Conditions

    Solution
    grade = float(input())
    if grade >= 5.5:
    print("Excellent")
    elif grade >= 4.5:
    print("Very good")
    elif grade >= 3.5:
    print("Good")
    elif grade >= 3:
    print("Average")
    else:
    print("Poor")
  12. 12. Hours to seconds

    Read a number of hours (a whole number) and print how many seconds that is.

    Input
    2
    Output
    7200 seconds

    What you need is in the lesson: Operators and arithmetic

    Solution
    hours = int(input())
    print(str(hours * 3600) + " seconds")
  13. 13. Count to N

    Read a whole number N and print the numbers from 1 to N, each on a new line.

    Input
    5
    Output
    1
    2
    3
    4
    5

    What you need is in the lesson: Loops

    Solution
    n = int(input())
    for i in range(1, n + 1):
    print(i)
  14. 14. ASCII value

    Read one character (the first character of the line) and print its ASCII code, the number the computer stores it as.

    Input
    A
    Output
    The code of A is 65.

    What you need is in the lesson: Strings: working with text

    Solution
    symbol = input()[0]
    print("The code of " + symbol + " is " + str(ord(symbol)) + ".")
  15. 15. Quadratic equation

    Read a, b and c, each on its own line, and solve ax² + bx + c = 0. With two roots print "x1 = …, x2 = …" (x1 uses +√D), with one root "x = …", with 2 decimal places; if there are no real roots or a is 0, say so.

    Input
    1
    -3
    2
    Output
    x1 = 2.00, x2 = 1.00

    What you need is in the lesson: Conditions

    Solution
    import math
    a = float(input())
    b = float(input())
    c = float(input())
    if a == 0:
    print("This is not a quadratic equation")
    else:
    d = b * b - 4 * a * c
    if d > 0:
    x1 = (-b + math.sqrt(d)) / (2 * a)
    x2 = (-b - math.sqrt(d)) / (2 * a)
    print(f"x1 = {x1:.2f}, x2 = {x2:.2f}")
    elif d == 0:
    print(f"x = {-b / (2 * a):.2f}")
    else:
    print("No real roots")
  16. 16. Positive or negative

    Read a whole number and print whether it is positive, negative or zero.

    Input
    -4
    Output
    Negative

    What you need is in the lesson: Conditions

    Solution
    number = int(input())
    if number > 0:
    print("Positive")
    elif number < 0:
    print("Negative")
    else:
    print("Zero")
  17. 17. Seasons

    Read a month number (1–12) and print its season: 12, 1, 2 are Winter, 3–5 Spring, 6–8 Summer, 9–11 Autumn. For any other number print "Invalid month".

    Input
    4
    Output
    Spring

    What you need is in the lesson: Conditions

    Solution
    month = int(input())
    if month < 1 or month > 12:
    print("Invalid month")
    elif month == 12 or month <= 2:
    print("Winter")
    elif month <= 5:
    print("Spring")
    elif month <= 8:
    print("Summer")
    else:
    print("Autumn")
  18. 18. Reverse a number

    Read a positive whole number and print the number with its digits in reverse order: 123 becomes 321. Zeros that end up in front disappear (1200 becomes 21). Take the last digit with % 10 and drop it by dividing by 10.

    Input
    9071
    Output
    1709

    What you need is in the lesson: Loops

    Solution
    n = int(input())
    reversed_n = 0
    while n > 0:
    reversed_n = reversed_n * 10 + n % 10
    n //= 10
    print(reversed_n)
  19. 19. Temperature converter

    Read a temperature in degrees Celsius (it may have a decimal point) and print it in Fahrenheit with two decimal places. The formula is F = C * 9 / 5 + 32.

    Input
    36.6
    Output
    97.88 °F

    What you need is in the lesson: Operators and arithmetic

    Solution
    celsius = float(input())
    fahrenheit = celsius * 9 / 5 + 32
    print(f"{fahrenheit:.2f} °F")
  20. 20. Longest name

    The first line holds the number of names n, and each of the next n lines holds one name. Print the name with the most letters and their count in brackets; if two names are equally long, print the first of them.

    Input
    4
    Mia
    Alexandra
    John
    Charlotte
    Output
    Alexandra (9 letters)

    What you need is in the lesson: Strings: working with text

    Solution
    n = int(input())
    longest = ""
    for i in range(n):
    name = input()
    if len(name) > len(longest):
    longest = name
    print(f"{longest} ({len(longest)} letters)")
  21. 21. Word counter

    Read one line of text and print how many words it has. Words are separated by one or more spaces, so the empty pieces between two spaces are not words.

    Input
    I write code every day and get better
    Output
    8

    What you need is in the lesson: Strings: working with text

    Solution
    line = input()
    words = line.split()
    print(len(words))
  22. 22. Prime number

    Read a whole number n and check whether it is prime: greater than 1 and divisible only by 1 and itself. It is enough to try the divisors i for which i * i <= n.

    Input
    91
    Output
    91 is not prime

    What you need is in the lesson: Loops

    Solution
    n = int(input())
    prime = n > 1
    i = 2
    while i * i <= n:
    if n % i == 0:
    prime = False
    break
    i += 1
    if prime:
    print(f"{n} is prime")
    else:
    print(f"{n} is not prime")
  23. 23. Day of the week

    Read a number from 1 to 7 and print the name of that day of the week, where 1 is Monday. Keep the names in an array; for any other number print "No such day".

    Input
    5
    Output
    Friday

    What you need is in the lesson: Lists

    Solution
    day = int(input())
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    if 1 <= day <= 7:
    print(days[day - 1])
    else:
    print("No such day")
  24. 24. Factorial

    Read a whole number n from 0 to 15 and print n! = 1 * 2 * ... * n (0! is 1). Already 13! does not fit in an int, so in Java and C# keep the product in a long.

    Input
    15
    Output
    15! = 1307674368000

    What you need is in the lesson: Loops

    Solution
    n = int(input())
    factorial = 1
    for i in range(2, n + 1):
    factorial *= i
    print(f"{n}! = {factorial}")
  25. 25. Valid date

    Read a day, a month and a year, each on its own line, and print "Valid date" or "Invalid date". The year is at least 1, the month is from 1 to 12 and the day from 1 to the number of days in that month; February has 29 days in a leap year (divisible by 4 but not by 100, unless it is divisible by 400).

    Input
    29
    2
    2100
    Output
    Invalid date

    What you need is in the lesson: Conditions

    Solution
    day = int(input())
    month = int(input())
    year = int(input())
    leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
    if month == 2:
    days = 29 if leap else 28
    elif month in (4, 6, 9, 11):
    days = 30
    else:
    days = 31
    if year >= 1 and 1 <= month <= 12 and 1 <= day <= days:
    print("Valid date")
    else:
    print("Invalid date")
  26. 26. Letter frequency

    Read one line of text and print how many times each letter appears in it, ignoring upper and lower case. Print the letters in alphabetical order, one per line, as "a: 5"; spaces and punctuation are not counted.

    Input
    Hello, World!
    Output
    d: 1
    e: 1
    h: 1
    l: 3
    o: 2
    r: 1
    w: 1

    What you need is in the lesson: dict and set

    Solution
    text = input().lower()
    counts = {}
    for c in text:
    if c.isalpha():
    counts[c] = counts.get(c, 0) + 1
    for c in sorted(counts):
    print(f"{c}: {counts[c]}")
  27. 27. Minimum and maximum in an array

    The first line holds the count n, and each of the next n lines holds one whole number. Read them into an array and print the smallest and the largest, starting from the first element and comparing it with the rest.

    Input
    5
    7
    -3
    12
    0
    4
    Output
    Smallest: -3
    Largest: 12

    What you need is in the lesson: Lists

    Solution
    n = int(input())
    numbers = []
    for i in range(n):
    numbers.append(int(input()))
    smallest = numbers[0]
    largest = numbers[0]
    for number in numbers:
    if number < smallest:
    smallest = number
    if number > largest:
    largest = number
    print(f"Smallest: {smallest}")
    print(f"Largest: {largest}")
  28. 28. Sort an array

    The first line holds the count n, and each of the next n lines holds one whole number. Sort them yourself in ascending order with bubble sort (n - 1 passes, each swapping neighbours that are in the wrong order) and print them on one line, separated by spaces.

    Input
    6
    5
    2
    9
    1
    5
    6
    Output
    1 2 5 5 6 9

    What you need is in the lesson: Lists

    Solution
    n = int(input())
    numbers = []
    for i in range(n):
    numbers.append(int(input()))
    for p in range(n - 1):
    for i in range(n - 1 - p):
    if numbers[i] > numbers[i + 1]:
    numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
    print(*numbers)
  29. 29. Replace the vowels

    Read one line of text and print it with every vowel, upper or lower case, replaced by the character *. The vowels are a, e, i, o, u.

    Input
    I love programming
    Output
    * l*v* pr*gr*mm*ng

    What you need is in the lesson: Strings: working with text

    Solution
    text = input()
    vowels = "aeiou"
    result = ""
    for c in text:
    if c.lower() in vowels:
    result += "*"
    else:
    result += c
    print(result)
  30. 30. Sum of the digits

    Read a whole non-negative number and print the sum of its digits. The last digit is n % 10, and n / 10 drops it (n // 10 in Python).

    Input
    9875
    Output
    29

    What you need is in the lesson: Loops

    Solution
    n = int(input())
    total = 0
    while n > 0:
    total += n % 10
    n //= 10
    print(total)
  31. 31. Palindrome

    Read one line of text and check whether it is a palindrome, that is, it reads the same backwards. Upper and lower case count as the same and spaces are skipped. Print "Palindrome" or "Not a palindrome".

    Input
    Never odd or even
    Output
    Palindrome

    What you need is in the lesson: Strings: working with text

    Solution
    text = input().lower().replace(" ", "")
    if text == text[::-1]:
    print("Palindrome")
    else:
    print("Not a palindrome")
  32. 32. Strong password

    Read passwords, one per line, until a strong one arrives: at least 8 characters, at least one digit, one uppercase and one lowercase letter. For each weak one print the first rule it breaks, in this order ("Too short", "No digit", "No uppercase letter", "No lowercase letter"); for the strong one print "Password accepted" and stop.

    Input
    kotka
    kotkamiau
    kotkamiau7
    Kotkamiau7
    Output
    Too short
    No digit
    No uppercase letter
    Password accepted

    What you need is in the lesson: Strings: working with text

    Solution
    while True:
    password = input()
    digit = False
    upper = False
    lower = False
    for c in password:
    if c.isdigit():
    digit = True
    elif c.isupper():
    upper = True
    elif c.islower():
    lower = True
    if len(password) < 8:
    print("Too short")
    elif not digit:
    print("No digit")
    elif not upper:
    print("No uppercase letter")
    elif not lower:
    print("No lowercase letter")
    else:
    print("Password accepted")
    break
  33. 33. Reverse an array

    The first line holds the count n, and each of the next n lines holds one whole number. Read them into an array and print them in reverse order on one line, separated by spaces: walk the array from the last index down to zero.

    Input
    4
    10
    -2
    7
    3
    Output
    3 7 -2 10

    What you need is in the lesson: Lists

    Solution
    n = int(input())
    numbers = []
    for i in range(n):
    numbers.append(int(input()))
    line = ""
    for i in range(n - 1, -1, -1):
    line += str(numbers[i])
    if i > 0:
    line += " "
    print(line)
  34. 34. Count the elements

    Read one line of words separated by single spaces and print how many times each word appears, as "word: count". The words come out in the order in which they first appeared.

    Input
    apple pear apple plum pear apple
    Output
    apple: 3
    pear: 2
    plum: 1

    What you need is in the lesson: dict and set

    Solution
    line = input()
    counts = {}
    for word in line.split(" "):
    counts[word] = counts.get(word, 0) + 1
    for word in counts:
    print(f"{word}: {counts[word]}")
  35. 35. Prime numbers

    Read a number N and print all prime numbers from 2 to N on one line, separated by spaces.

    Input
    30
    Output
    2 3 5 7 11 13 17 19 23 29

    What you need is in the lesson: Loops

    Solution
    n = int(input())
    primes = []
    for i in range(2, n + 1):
    prime = True
    d = 2
    while d * d <= i:
    if i % d == 0:
    prime = False
    break
    d += 1
    if prime:
    primes.append(str(i))
    print(" ".join(primes))
  36. 36. Average

    One line holds whole numbers separated by spaces. Print their average with two digits after the decimal point.

    Input
    5 8 12 6
    Output
    Average: 7.75

    What you need is in the lesson: Lists

    Solution
    parts = input().split()
    total = 0
    for part in parts:
    total += int(part)
    average = total / len(parts)
    print(f"Average: {average:.2f}")
  37. 37. Sort by length

    One line holds words separated by spaces. Sort them by length from shortest to longest (words of equal length keep their input order) and print them on one line.

    Input
    cherry fig banana kiwi plum
    Output
    fig kiwi plum cherry banana

    What you need is in the lesson: Strings: working with text

    Solution
    words = input().split()
    for i in range(len(words) - 1):
    for j in range(len(words) - 1 - i):
    if len(words[j]) > len(words[j + 1]):
    words[j], words[j + 1] = words[j + 1], words[j]
    print(" ".join(words))
  38. 38. Sentence counter

    Read one line of text and print how many sentences it has. A sentence ends with a full stop, an exclamation mark or a question mark; a run of such marks (like "..." or "?!") is a single ending.

    Input
    Hi! How are you? I am fine... And you?!
    Output
    Sentences: 4

    What you need is in the lesson: Strings: working with text

    Solution
    text = input()
    ends = ".!?"
    count = 0
    for i in range(len(text)):
    is_end = text[i] in ends
    next_is_end = i + 1 < len(text) and text[i + 1] in ends
    if is_end and not next_is_end:
    count += 1
    print(f"Sentences: {count}")
  39. 39. Fibonacci numbers

    The Fibonacci sequence starts with 1, 1, and every next number is the sum of the previous two. Read N (from 1 to 50) and print the N-th number of the sequence.

    Input
    40
    Output
    102334155

    What you need is in the lesson: Loops

    Solution
    n = int(input())
    previous = 0
    current = 1
    for i in range(1, n):
    previous, current = current, previous + current
    print(current)
  40. 40. Finding the median

    One line holds whole numbers separated by spaces. Print their median with one digit after the decimal point: the middle number once they are sorted, or the mean of the two middle ones when the count is even.

    Input
    12 3 7 9 1 8
    Output
    Median: 7.5

    What you need is in the lesson: Lists: append, remove and sort

    Solution
    numbers = []
    for part in input().split():
    numbers.append(int(part))
    numbers.sort()
    n = len(numbers)
    if n % 2 == 1:
    median = numbers[n // 2]
    else:
    median = (numbers[n // 2 - 1] + numbers[n // 2]) / 2
    print(f"Median: {median:.1f}")
  41. 41. Character chart

    Read one line of text. For every character except the space, in order of first appearance, print a line "character | stars" with one star for each time it occurs in the text.

    Input
    banana bread
    Output
    b | **
    a | ****
    n | **
    r | *
    e | *
    d | *

    What you need is in the lesson: Strings: working with text

    Solution
    text = input()
    for i in range(len(text)):
    c = text[i]
    if c != " " and text.index(c) == i:
    count = 0
    for other in text:
    if other == c:
    count += 1
    print(c + " | " + "*" * count)
  42. 42. Transposing a matrix

    The first line holds the number of rows R and columns C, followed by R lines of C numbers separated by spaces. Print the transposed matrix: C lines of R numbers, where rows become columns.

    Input
    2 3
    1 2 3
    4 5 6
    Output
    1 4
    2 5
    3 6

    What you need is in the lesson: Two-dimensional arrays

    Solution
    size = input().split()
    rows = int(size[0])
    cols = int(size[1])
    matrix = []
    for r in range(rows):
    row = []
    for part in input().split():
    row.append(int(part))
    matrix.append(row)
    for c in range(cols):
    line = []
    for r in range(rows):
    line.append(str(matrix[r][c]))
    print(" ".join(line))
  43. 43. Paths in a maze

    The first line holds R and C, followed by R lines of C characters: "." is a free cell and "#" is a wall. Moving only right or down and never stepping on a wall, print the number of all paths from the top-left to the bottom-right corner.

    Input
    4 5
    .....
    .#.#.
    ...#.
    #....
    Output
    Paths: 4

    What you need is in the lesson: Recursion

    Solution
    def count_paths(maze, r, c):
    if r >= len(maze) or c >= len(maze[0]) or maze[r][c] == "#":
    return 0
    if r == len(maze) - 1 and c == len(maze[0]) - 1:
    return 1
    return count_paths(maze, r + 1, c) + count_paths(maze, r, c + 1)
    size = input().split()
    rows = int(size[0])
    maze = []
    for r in range(rows):
    maze.append(input())
    print(f"Paths: {count_paths(maze, 0, 0)}")
  44. 44. Grade statistics

    One line holds grades from 2 to 6 (the Bulgarian school scale, 6 is best), separated by spaces. Print how many are excellent, very good, good, satisfactory and poor, each category on its own line.

    Input
    6 4 5 6 3 5 2 6 5 4
    Output
    Excellent (6): 3
    Very good (5): 3
    Good (4): 2
    Satisfactory (3): 1
    Poor (2): 1

    What you need is in the lesson: Lists

    Solution
    names = ["", "", "Poor", "Satisfactory", "Good", "Very good", "Excellent"]
    counts = [0] * 7
    for part in input().split():
    counts[int(part)] += 1
    for grade in range(6, 1, -1):
    print(f"{names[grade]} ({grade}): {counts[grade]}")
  45. 45. Roman numerals

    Read a whole number from 1 to 3999 and print it in Roman numerals (I, V, X, L, C, D, M, where 4 is IV, 9 is IX, 40 is XL and so on).

    Input
    1994
    Output
    MCMXCIV

    What you need is in the lesson: Lists

    Solution
    number = int(input())
    values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
    roman = ""
    for i in range(len(values)):
    while number >= values[i]:
    roman += symbols[i]
    number -= values[i]
    print(roman)
  46. 46. Coin toss simulation

    Read a seed x (from 1 to 2147483646) and a number of tosses N, each on its own line. On every toss set x = x * 16807 % 2147483647; an even x is heads (H), an odd x is tails (T). Print the tosses on one line, then how many heads and how many tails came up.

    Input
    42
    10
    Output
    HTTTHTTHHT
    Heads: 4
    Tails: 6

    What you need is in the lesson: Loops

    Solution
    x = int(input())
    n = int(input())
    tosses = ""
    heads = 0
    for i in range(n):
    x = x * 16807 % 2147483647
    if x % 2 == 0:
    tosses += "H"
    heads += 1
    else:
    tosses += "T"
    print(tosses)
    print(f"Heads: {heads}")
    print(f"Tails: {n - heads}")
  47. 47. Symmetric array

    One line holds whole numbers separated by spaces. Check whether the array is symmetric, that is, it reads the same from left to right and from right to left.

    Input
    1 2 3 2 1
    Output
    Symmetric

    What you need is in the lesson: Lists

    Solution
    numbers = []
    for part in input().split():
    numbers.append(int(part))
    symmetric = True
    for i in range(len(numbers) // 2):
    if numbers[i] != numbers[len(numbers) - 1 - i]:
    symmetric = False
    break
    print("Symmetric" if symmetric else "Not symmetric")
  48. 48. Balanced brackets

    Read one line of text and check whether its brackets (), [] and {} are balanced: every opening bracket has a closing one of the same kind and the pairs do not cross. Other characters are ignored.

    Input
    (a + [b) * c]
    Output
    Not balanced

    What you need is in the lesson: Stack, queue and linked list

    Solution
    text = input()
    opening = "([{"
    closing = ")]}"
    stack = []
    balanced = True
    for c in text:
    if c in opening:
    stack.append(c)
    elif c in closing:
    if not stack or opening.index(stack.pop()) != closing.index(c):
    balanced = False
    break
    if balanced and not stack:
    print("Balanced")
    else:
    print("Not balanced")
  49. 49. Run of equal elements

    One line holds whole numbers separated by spaces. Find the longest run of equal neighbouring numbers and print it on one line; if several runs have the same length, print the first one.

    Input
    2 1 1 3 3 3 2 2 2 5
    Output
    3 3 3

    What you need is in the lesson: Lists

    Solution
    numbers = []
    for part in input().split():
    numbers.append(int(part))
    best_value = numbers[0]
    best_length = 1
    length = 1
    for i in range(1, len(numbers)):
    if numbers[i] == numbers[i - 1]:
    length += 1
    else:
    length = 1
    if length > best_length:
    best_length = length
    best_value = numbers[i]
    print(" ".join([str(best_value)] * best_length))
  50. 50. Shortest path in a grid

    The first line holds R and C, followed by R lines of C characters: "." is a free cell, "#" is a wall, "S" is the start and "E" is the goal. Moving up, down, left and right, print the smallest number of moves from S to E, or "No path" if E cannot be reached.

    Input
    5 6
    S.#...
    .##.#.
    ...#..
    #.#..#
    ...E.#
    Output
    7

    What you need is in the lesson: Stack, queue and linked list

    Solution
    from collections import deque
    size = input().split()
    rows = int(size[0])
    cols = int(size[1])
    grid = []
    for r in range(rows):
    grid.append(input())
    dist = []
    queue = deque()
    for r in range(rows):
    dist.append([-1] * cols)
    for c in range(cols):
    if grid[r][c] == "S":
    dist[r][c] = 0
    queue.append((r, c))
    moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    answer = "No path"
    while queue:
    r, c = queue.popleft()
    if grid[r][c] == "E":
    answer = str(dist[r][c])
    break
    for dr, dc in moves:
    nr = r + dr
    nc = c + dc
    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != "#" and dist[nr][nc] == -1:
    dist[nr][nc] = dist[r][c] + 1
    queue.append((nr, nc))
    print(answer)

Language basics

Functions

Classes and objects

Inheritance and polymorphism

Errors and exceptions

Text and files

Collections

Modern Python

Real-world programs

  • Tests with unittest: The discount calculator · The account · The bug in the average grade
  • Threads: Parallel sum · Downloading with a pool · A counter without losses
  • Network programming: Echo server · A server with commands · A chat for two
  • Databases: Catalog · Search by part of the name · A transfer that fails halfway
  • Reflection and decorators: All the fields, class by class · Mini JSON · Your own test runner

Let's make a game

Chronicles of Arcanum

Epic Cosmos: the empire

Project

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·