priority study notes Flashcards

1
Q

An airport is empty in the morning. During the day, planes land and also take off. At the end of the day, the field is either empty, or has one plane not taking off. An airplane can land and take off several times. Each plane has a tail number (integer up to 4 digits).

  • write a function that receives two lists (landing and taking off), and returns an answer if the field is empty at the end of the day or the tail number of te aircraft left there.

-Write a function that receives only one list of planes (landing or taking off) and does the same. (First plane lands and then takes off)

A

def check_airport_flights(landing, taking_off):
planes = {}

for plane in landing:
    planes[plane] = planes.get(plane, 0) + 1

for plane in taking_off:
    if plane in planes:
        planes[plane] -= 1
        if planes[plane] == 0:
            del planes[plane]

if len(planes) == 0:
    return "Empty Field"
else:
    return list(planes.keys())[0]

def check_airport_flights_one_list(plane_list):
remaining_planes = 0

for plane in plane_list:
    remaining_planes ^= plane

return remaining_planes

if __name__ == “__main__”:
landing_planes = [1234, 5678, 9012, 3456, 5678, 5678, 5678]
taking_off_planes = [5678, 3456, 5678, 5678, 1234]

result = check_airport_flights(landing_planes, taking_off_planes)
print(result)

planes_list = [1234, 5678, 9012, 9012, 3456, 5678, 3456]
result = check_airport_flights_one_list(planes_list)
print(result)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write a function to determine if a number is a palindrome.

A

def is_palindrome(str) -> bool:
return str == str[::-1]

if __name__ == “__main__”:
test_cases = {
“1223221”,
“12”,
“”,
“-1223221”,
“wow”,
“barda”,
“hannah”
}

for test in test_cases:
	pal = is_palindrome(test)
	print(f"Is this palindrome {test}: {pal}")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Write a function that converts a roman numeral to the decimal system

A

def roman_to_decimal(str):
roman_values = {
‘I’: 1,
‘V’: 5,
‘X’: 10,
‘L’: 50,
‘C’: 100,
‘D’: 500,
‘M’: 1000
}

res = 0
i = 0

while i < len(str):
    value_of_str = roman_values.get(str[i], 0)

    if i + 1 < len(str):
        next_value_of_str = roman_values.get(str[i + 1], 0)

        if value_of_str >= next_value_of_str:
            res += value_of_str
            i += 1
        else:
            res += next_value_of_str - value_of_str
            i += 2
    else:
        res += value_of_str
        i += 1

return res

if __name__ == “__main__”:
tests = {
“MCLXVI”: “1166”,
“IV”: “4”,
“IX”: “9”,
“XC”: “90”,
“MDCCLXXVII”: “1777”
}

for roman_numeral, expected_decimal in tests.items():
    print(f"The Roman number is: {roman_numeral}")
    res = roman_to_decimal(roman_numeral)
    print(f"After converting to decimal: {res}")
    assert str(res) == expected_decimal
    print("Conversion is correct!\n")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is an errr? What is an exception? What types of exceptions are you familiar with?

A

An error refers to when we have a mistake in the program, meaning it won’t let the program run at all. Example for an error is a syntax error.
An exception refers to a specific type of an error that can be caught and handled by us. They allow us to handle the errors in any way we want.
Examples for Exceptions:
ValueError => Invalid value
ZeroDivisionError => Cannot divide by 0
IndexError => Trying to access elements of a list out of range index
FileNotFoundError => Attempting to open an unexisting file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Write a function that gets an array of red, yellow and green balls.

sort the array so that the green balls are at the beginning and the red ones at the end.

There is no additional memory space to use.

A

def sort_balls_by_colours(balls):
green_ball = 0 #left pointer for the green balls
red_ball = len(balls) - 1 #right pointer for the red balls
current_ball = 0 #current pointer

while current_ball <= red_ball:
	if balls[current_ball] == "green":
		balls[green_ball], balls[current_ball] = balls[current_ball], balls[green_ball]
		green_ball += 1
		current_ball += 1
	elif balls[current_ball] == "red":
		balls[red_ball], balls[current_ball] = balls[current_ball], balls[red_ball]
		red_ball -= 1
	else:
		current_ball += 1

if __name__ == “__main__”:
balls = [“green”, “red”, “yellow”,”green”, “red”, “yellow”,”green”, “red”, “yellow”]
print(“Balls before the sort: “, balls)
sort_balls_by_colours(balls)
print(“Balls after being sort by colour: “, balls)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write a python function that gets a number, and replaces one of the digits with a ‘5’ to achieve the highest number

A

def replace_with_five(num):
num_str = str(num)
num_digits = len(num_str)

for i in range(num_digits):
	if int(num_str[i]) < 5:
		num_str = num_str[:i] + '5' + num_str[i+1:]
		return int(num_str)

return num

if __name__ == ‘__main__’:
print(f”Original number: {666}”)
print(“After replacing with five:”)
highest = replace_with_five(666)
print(f”{highest}”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Explain the stages of the software development life cycle (SDLC) with reference to who we interact with, as DevOps people

A

The Software Development Life Cycle (SDLC) is a structured framework used by software development teams to guide the process of creating, testing, and maintaining software systems. It consists of several stages:

1 - Requirements Gathering: Identifying and documenting user needs and expectations.

2 - System Design: Creating a detailed plan for the software solution, including architecture and components.

3 - Implementation: Writing code, conducting unit testing, and integrating components.

4 - Testing: Verifying software quality through various tests like unit, integration, system, and user acceptance testing.

5 - Deployment: Releasing the software to production or making it available to users.

6 - Maintenance: Addressing bugs, updates, and enhancements throughout the software's lifecycle.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Write a function IsSumFound that recieves a sorted array of int numbers, and a sum, also of type int.

The function returns 1, if two numbers in the array are found that sum up to the sum number, and 0 otherwise. if two such numbers are found, then the function should also return the indexes of the two numbers that sum up to the sum.

For example, if the array is 2 4 7 12 14 and the sum is 21, then the sum is found.
if the sum is 4, 30 or 13, then the sum is not found. Run over the array exactly once.

A

def IsSumFound(arr, target_sum):
left = 0
right = len(arr) - 1

while left < right:
	current_sum = arr[left] + arr[right]
	
	if current_sum == target_sum:
		return 1, left, right
		
	if current_sum < target_sum:
		left += 1
	
	else:
		right -= 1
	
	
return 0, -1, -1

arr = [ 2, 4, 7, 12, 14]
target_sum = 21

result, index1, index2 = IsSumFound(arr, target_sum)

if result:
print(f”Sum found at indexes {index1} and {index2}.”)
else:
print(“Sum is not found”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the following commands used for?
-ip
-addr
-ip route
-ip link
-ping
-netstat
-traceroute

A

ip: The ip command is used to manipulate and display network-related settings in Linux. It provides a comprehensive set of tools for configuring network interfaces, routing tables, and more.

addr: The ip addr command is a subcommand of the ip command and is used to display and manage IP addresses assigned to network interfaces on a Linux system. It shows information about both IPv4 and IPv6 addresses, along with associated network details. 
addr it self is not a command

ip route: The ip route command, also a subcommand of ip, is used to view and manage the routing table on a Linux system. It displays the routing entries that define how network traffic is forwarded between different networks or subnets.

ip link: Another subcommand of ip, ip link, is used to manage network interfaces on a Linux system. It allows you to view information about available network interfaces, bring them up or down, change their settings, and more.

ping: The ping command is used to test the reachability of a network host or IP address by sending ICMP (Internet Control Message Protocol) echo request packets and waiting for ICMP echo reply packets. It helps determine if a host is active or if there are network connectivity issues.

netstat: The netstat command is used to display various network-related information on a Linux system, such as active network connections, listening ports, routing tables, network interface statistics, and more. It provides insights into network connections and overall network activity.

traceroute: The traceroute command is used to trace the route that packets take from your computer to a destination IP address or hostname. It shows the IP addresses of intermediate network hops along with the round-trip time (RTT) for each hop, helping to diagnose network routing and connectivity issues.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Describe the boot process of a linux machine, from power on to system ready.

A
  • Question 1:
  1. BIOSBIOS stands for Basic Input/Output System
    Performs some system integrity checks
    Searches, loads, and executes the boot loader program.
    It looks for boot loader in floppy, cd-rom, or hard drive. You can press a key (typically F12 of F2, but it depends on your system) during the BIOS startup to change the boot sequence.
    Once the boot loader program is detected and loaded into the memory, BIOS gives the control to it.
    So, in simple terms BIOS loads and executes the MBR boot loader.
  2. MBRMBR stands for Master Boot Record.
    It is located in the 1st sector of the bootable disk. Typically /dev/hda, or /dev/sda
    MBR is less than 512 bytes in size. This has three components 1) primary boot loader info in 1st 446 bytes 2) partition table info in next 64 bytes 3) mbr validation check in last 2 bytes.
    It contains information about GRUB (or LILO in old systems).
    So, in simple terms MBR loads and executes the GRUB boot loader.
  3. GRUBGRUB stands for Grand Unified Bootloader.
    If you have multiple kernel images installed on your system, you can choose which one to be executed.
    GRUB displays a splash screen, waits for few seconds, if you don’t enter anything, it loads the default kernel image as specified in the grub configuration file.
    GRUB has the knowledge of the filesystem (the older Linux loader LILO didn’t understand filesystem).
    Grub configuration file is /boot/grub/grub.conf (/etc/grub.conf is a link to this). The following is sample grub.conf of CentOS.#boot=/dev/sda
    default=0
    timeout=5
    splashimage=(hd0,0)/boot/grub/splash.xpm.gz
    hiddenmenu
    title CentOS (2.6.18-194.el5PAE)
    root (hd0,0)
    kernel /boot/vmlinuz-2.6.18-194.el5PAE ro root=LABEL=/
    initrd /boot/initrd-2.6.18-194.el5PAE.imgAs you notice from the above info, it contains kernel and initrd image.
    So, in simple terms GRUB just loads and executes Kernel and initrd images.
  4. KernelMounts the root file system as specified in the “root=” in grub.conf
    Kernel executes the /sbin/init program
    Since init was the 1st program to be executed by Linux Kernel, it has the process id (PID) of 1. Do a ‘ps -ef | grep init’ and check the pid.
    initrd stands for Initial RAM Disk.
    initrd is used by kernel as temporary root file system until kernel is booted and the real root file system is mounted. It also contains necessary drivers compiled inside, which helps it to access the hard drive partitions, and other hardware.
  5. InitLooks at the /etc/inittab file to decide the Linux run level.
    Following are the available run levels
    0 – halt
    1 – Single user mode
    2 – Multiuser, without NFS
    3 – Full multiuser mode
    4 – unused
    5 – X11
    6 – reboot
    Init identifies the default initlevel from /etc/inittab and uses that to load all appropriate program.
    Execute ‘grep initdefault /etc/inittab’ on your system to identify the default run level
    If you want to get into trouble, you can set the default run level to 0 or 6. Since you know what 0 and 6 means, probably you might not do that.
    Typically you would set the default run level to either 3 or 5.
  6. Runlevel programsWhen the Linux system is booting up, you might see various services getting started. For example, it might say “starting sendmail …. OK”. Those are the runlevel programs, executed from the run level directory as defined by your run level.
    Depending on your default init level setting, the system will execute the programs from one of the following directories.
    Run level 0 – /etc/rc.d/rc0.d/
    Run level 1 – /etc/rc.d/rc1.d/
    Run level 2 – /etc/rc.d/rc2.d/
    Run level 3 – /etc/rc.d/rc3.d/
    Run level 4 – /etc/rc.d/rc4.d/
    Run level 5 – /etc/rc.d/rc5.d/
    Run level 6 – /etc/rc.d/rc6.d/
    Please note that there are also symbolic links available for these directory under /etc directly. So, /etc/rc0.d is linked to /etc/rc.d/rc0.d.
    Under the /etc/rc.d/rc*.d/ directories, you would see programs that start with S and K.
    Programs starts with S are used during startup. S for startup.
    Programs starts with K are used during shutdown. K for kill.
    There are numbers right next to S and K in the program names. Those are the sequence number in which the programs should be started or killed.
    For example, S12syslog is to start the syslog deamon, which has the sequence number of 12. S80sendmail is to start the sendmail daemon, which has the sequence number of 80. So, syslog program will be started before sendmail.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Explain what the following commands do?

1) find /home -iname temp.out:

2) find / -type d -name Infinity:

3) find . -type f -name “*.c”:

4) find / -type f -perm 0777 -print -exec chmod 644 {} ;:

5) find . -type f -name “do.txt” -exec rm -f {} ;:

6) find . -ipath “.//[C|c]//*.c” -exec gedit {} + &:

7) awk ‘{print “Good Morning “}’:

8) awk -F: ‘{print $1}’ /etc/passwd:

A

1) find /home -iname temp.out:
This command searches for a file named “temp.out” in the directory /home and its subdirectories. The search is case-insensitive (-iname flag), so it will match files with names like “temp.out”, “Temp.out”, or “TEMP.OUT”.

2) find / -type d -name Infinity:
This command searches for directories with the name “Infinity” starting from the root directory (“/”). The -type d flag ensures that only directories are considered.

3) find . -type f -name “.c”:
This command searches for files with the extension “.c” in the current directory and its subdirectories. The -type f flag ensures that only regular files are considered, and the -name “
.c” flag specifies the file name pattern to match.

4) find / -type f -perm 0777 -print -exec chmod 644 {} ;:
This command searches for files with permissions set to 0777 (read, write, and execute permissions for all users) starting from the root directory (“/”). It then prints the file paths (-print) and uses the -exec flag to execute the chmod command, changing the permissions of each file to 644 (read and write for the owner, and read-only for group and others).

5) find . -type f -name “do.txt” -exec rm -f {} ;:
This command searches for files named “do.txt” in the current directory and its subdirectories. Once found, it executes the rm -f command to forcefully remove each file. The -f flag ensures that files are deleted without prompting for confirmation.

6) find . -ipath “.//[C|c]//.c” -exec gedit {} + &:
This command searches for files with names ending in “.c” in any subdirectory of the current directory. The -ipath flag performs a case-insensitive search, and the pattern “./
/[C|c]//.c” matches paths where the directory name contains either “C” or “c”. For each matching file, it executes the gedit command to open it in a text editor. The + symbol groups the files together to be opened in a single instance of gedit, and the & runs the command in the background.

7) awk ‘{print “Good Morning “}’:
This command uses the awk tool to process input line by line. In this case, it simply prints the text “Good Morning “ for each line of input.

8) awk -F: ‘{print $1}’ /etc/passwd:
This command uses awk to process the file “/etc/passwd”. The -F: flag specifies that the field separator is a colon. The command then prints the first field ($1), which corresponds to the usernames in the passwd file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the differences between broadcast, multicast and unicast?

What is ARP? ARP Cache? Gratuitious ARP?

What is a port number, and what is it used for?

A
  • Unicast: one to one connection
    Broadcast: one to all connection
    Multicast: one to multiple recepients connection
  • ARP: A protocol that maps IP Addresses to MAC Addresses
    ARP Cache: Is a collection of IP-MAC Addresses relationships that are stored in a table
    ARP Gratuitous: A Gratuitous ARP is an ARP Response that was not prompted by an ARP Request.
    The Gratuitous ARP is sent as a broadcast, as a way for a node to announce or update its IP to MAC mapping to the entire network.
  • A port number is a way to identify a specific process to which an internet or other network message is to be forwarded when it arrives at a server.
    The use of ports and their identifying numbers are an extension to the addressing scheme.
    Once the address is used to deliver data to the wanted host on the network, the port number is used to identify the process for which the data is used.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

If you set a system’s subnet mask to 25.255.255.0, how many computers can you put on the network without using a router?

Given the network address 128.0.16.100/16, how many hosts may exist on this network?

Explain the need for IP addresses. Why are MAC addresses not sufficient?

A

The meaning of 255.255.255.0 subnet mask is it’s devided to 24 bits for Net ID and 8 bits for Host ID,
meaning that we can connect only 2^8 ip addresses which is equal to 256,
but the first one is for the net id while the last one is for broadcast id which means 254 are available.

because it’s /16 meaning that the ip is divided to 16 bits for network, and 16 bits for host meaning 2^8 * 2^8 - ( 2 ).

IP addresses are necessary because they provide a logical addressing scheme that enables communication between devices across networks, including the internet. While MAC addresses uniquely identify devices within a local network, they are not sufficient for routing data across multiple networks due to their hardware-based nature and lack of scalability. IP addresses offer flexibility, scalability, and standardized protocols for efficient network communication.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

On which OSI Layers do the following protocols run?
-HTTP
-UDP
-ARP
-Ethernet
-IP

What is NAT? What is it used for?

A
  • Question 7:
    HTTP -> Layer 7 - Application Layer
    UDP -> Layer 4 - Transport Layer
    ARP -> Layer 2 - Data Link Layer
    Ethernet -> Layer 2 - Data Link Layer
    IP -> Layer 3 - Network Layer
  • Question 8:
    NAT stands for network address translation.
    It’s a way to map multiple private addresses inside a local network to a public IP address before transferring the information onto the internet.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the differences between a switch and a hub?

What is the meaning of HTTP 200 status code?

A

Hub and Switch are the network connecting devices, both help to connect various devices. Hub works at the physical layer and transmits the signal to the port. Switch route the information and send it over the network.

The 200 OK status code means that the request was successful.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Given an array of values 0 and 1, implement a function that sorts the 0 to the beginning and 1 to the end. Required complexity 0(n).

use swapping

A

include <stdio.h></stdio.h>

void SortZerosAndOnes(int arr[], int size)
{
int left = 0; /* Pointer for the leftmost element /
int right = size - 1; /
Pointer for the rightmost element */
int temp;

while (left < right) 
{
    /* Move the left pointer until a 1 is found */
    while (arr[left] == 0 && left < right) 
    {
        left++;
    }

    /* Move the right pointer until a 0 is found */
    while (arr[right] == 1 && left < right) 
    {
        right--;
    }

    /* Swap the elements at left and right */
    if (left < right) 
    {
        temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
    }
} }
17
Q

Check for balanced parentheses i an expression.

Write a function to examine whether the pairs of parentheses {}, (), [] are correct in a given string.

A

int IsParenthesesValid(const char *str)
{
int parentheses = 0;
int curly_braces = 0;
int square_brackets = 0;
int i;

for (i = 0; str[i] != '\0'; ++i) 
{
    if (str[i] == '(')
    {        
        \++parentheses;
    }
    else if (str[i] == ')')
   	{       	
        --parentheses;
   	}
    else if (str[i] == '{')
    {
        \++curly_braces;        
    }
    else if (str[i] == '}')
    {
        --curly_braces;
    }
    else if (str[i] == '[')
    {
        \++square_brackets;
    }
    else if (str[i] == ']')
    {
        --square_brackets;
    }

    /* If any count becomes negative, there is a closing symbol without an opening one */
    if (parentheses < 0 || curly_braces < 0 || square_brackets < 0)
        return 1;
}