Basic 1:

Return a+b

Basic 2:

Array

for x in ar:
  sum += x

Basic 3:

Array Python

# Stupid Init
- result = [0,0]
# Append
- cars.append("Honda")
# Pop
- cars.pop(1)
# Remove
- cars.remove("Volvo")

If Python

If ...:
elif ...:
else:

Basic 4:

File

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    a = list(map(int, input().rstrip().split()))

    b = list(map(int, input().rstrip().split()))

    result = compareTriplets(a, b)

    fptr.write(' '.join(map(str, result)))
    fptr.write('\n')

    fptr.close()

Basic 5:

For in For Abs different in 2D array

for i in range(n):
        for j in range(n):
            if (i==j):
                x += arr[i][j]
            if (i==(n-1-j)):
                y += arr[i][j]

Abs in Python

abs (x)

Basic 6:

Print

print (positiveRate)

Default: auto break line

To get float

x = float (y/z)

Print (float (y/z))

Basic 8:

Print staircase

for i in range(n):
    for j in range(n):
        if j < n-i-1 :
            print (" ", end ="")
        elif j == n-1:
            print ("#")
        else :
            print ("#", end ="")

Print staircase ver2

for x in range(n):
        for y in range(n):
            if y < m:
                print (' ', end='')
            elif y >= m:
                print ('#', end='')
        m-=1
        print ('')

Print ln = print ("") Should not use print ("\n”) because of default line break

Basic 9:

Grading Students

for i in range(grades_count):
        if grades[i] < 38:
            grades[i] = grades[i]
        else:
            if ((grades[i]%5) == 3):
                grades[i] = grades[i]+2
            if ((grades[i]%5) == 4):
                grades[i] = grades[i]+1   
    return grades

Note: should not use for x, cannot change value in array when using that way

2020-02-08

Basic 10:

Given a string, , of length that is indexed from to , print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail).

S = ""
ar = []
n = int(input())
for i in range (0,n):
    s = input()
    length = len(s)
    for j in range (0,length):
        if j%2 == 0:
            print (s[j], end = "")
    print (" ", end ="")
    for j in range (0,length):
        if j%2 != 0:
            print (s[j], end = "")
    print ("")

Basic 11:

input to array:

arr = list(map(int, input().rstrip().split()))

Given an array, , of integers, print ‘s elements in reverse order as a single line of space-separated numbers.

for i in reversed(range(n)):
        print(arr[i], end = " ")

Basic 12:

sockMerchant how to count and pair socks in the store

def sockMerchant(n, ar):
    ar.sort()
    count = []
    result = 0
    append = ar.count(ar[0])
    count.append(append)
    for i in range(n-1):
        if ar[i] != ar[i+1]:
            append = ar.count(ar[i+1])
            count.append(append)
    for x in count:
        result = result + x//2
    return result

Basic 13:

Counting Valleys

def countingValleys(n, s):
    sum = flagDown = flagUp = 0
    track = []
    track.append(sum)
    count = 0
    for i in range (n):
        if s[i] == "D":
            sum = sum - 1
            track.append(sum)
        elif s[i] == "U":
            sum = sum + 1
            track.append(sum)
    t = len(track)
    for j in range(1, t):
        if (track[j-1] < track[j]):
            flagUp = 1
            flagDown = 0
        if (track[j-1] > track[j]):
            flagDown = 1
            flagUp = 0
        if (track[j] == 0) and flagUp == 1:
            count = count + 1
    return count    

Basic 14:

Jumping on Cloud

def jumpingOnClouds(c):
    i = 0
    count = 0
    while (i < n-2):
        if c[i] == 0 and c[i+2] == 0:
            i = i+2
            count += 1
        else:
            i = i+1
            count += 1
    if (i==n-1):
        count = count
    else:
        count = count + 1
    return count

Basic 15:

Repeated String:

def repeatedString(s, n):
    count = countEach = countSpec = 0
    newstr = modstr = ""
    leng = len(s)   
    repeat = n // leng
    mod = n % leng
    if mod == 0:
        countSpec = 0
    elif mod == 1:
        modstr = s[0]
        if s[0] == 'a':
            countSpec = 1
    else:
        strmod = mod - 1
        modstr = s[0:strmod]
        for i in range (mod):
            if s[i] == "a":
                countSpec += 1
    for i in range (leng):
        if s[i] == "a":
            countEach += 1

    count = countEach*repeat+countSpec
    return count

Basic 16:

Apple Trees

countApples = countOranges = 0
    for i in range (m):
        apples[i] = apples[i] + a
        if apples[i] >= s and apples[i] <= t:
            countApples += 1

    for i in range (n):
        oranges[i] = oranges[i] + b
        if oranges[i] >= s and oranges[i] <= t:
            countOranges += 1
    print (countApples)
    print (countOranges)

Note: just need to read description carefully and understand variables

Basic 17:

Kangaroo

flag = count = 0
    result = ""
    if v1 <= v2:
        flag = 0
    else:
        while (x1 <= x2):
            x1 = x1 + v1
            x2 = x2 + v2
            if x1 == x2:
                flag = 1
    if flag == 1:
        result = "YES"
    else:
        result = "NO"
    return result

Basic 18:

Dictionary

n = int(input().strip())
phonebook = {}
for i in range(n):
    line = input()
    k, v = line.split()
    phonebook[k] = v

while True:
    try:
        number = input()
    except EOFError:
        break
    if number in phonebook:
        print("{}={}".format(number, phonebook[number]))
    else:
        print("Not found")

Read input to line Split line to get specific value to specific Variables Dictionary init: Dic[key] = value

Print Dictionary: print("{}={}".format(number, phonebook[number]))

Reduce timeout: while, try except…

Basic 19:

Recursive

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

Basic 20:

2D Array, hourglassSum

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the hourglassSum function below.
def hourglassSum(arr):
    max = arr[0][0] + arr[0][1] + arr[0][2] + arr[1][1] + arr[2][0] + arr[2][1] + arr[2][2]
    for i in range (4):
        for j in range (4):
            sum = arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]
            if sum > max:
                max = sum
                sum = 0
            else:
                sum = 0
    return max



if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    arr = []

    for _ in range(6):
        arr.append(list(map(int, input().rstrip().split())))

    result = hourglassSum(arr)

    fptr.write(str(result) + '\n')

    fptr.close()

Basic 21:

Rotate

def rotLeft(a, d):
    b = []
    for i in range (n):
        t = (i+d)
        if (t>=n):
            t = t%n
        b.append(a[t])
        print (i, t)
    return b