Python: How Many Chocolates?

Sanjay loves chocolates. He goes to a shop to buy his favourite chocolate. There he notices there is an offer going on, upon bringing 3 wrappers of the same chocolate, you will get new chocolate for free. If Sanjay has m Rupees. How many chocolates will he be able to eat if each chocolate costs c Rupees?

----------------------------------------------------------------------
Input:
Two positive integers m and c separated by a comma. The first integer is m and the second integer is c

Output:
A single integer denoting the number of chocolates Sanjay was able to eat in total.

----------------------------------------------------------------------
Sample input:
15, 2

Sample output:
10

Explanation:
First, he will get 15/2=7 chocolates. He then will return 6 wrappers for 2 chocolates. And lastly, these two wrappers and the one he previously had will get him one more chocolate, making a total of 7+2+1=10 chocolates.

----------------------------------------------------------------------
Sample input:
3,1

Sample output:
4

Solution

#take input here
mystring = input()
mylist = mystring.split(',')

m = int(mylist[0])
c = int(mylist[1])

#start writing your code here

choc = m//c
w = m//c

while w//3!=0:
    choc = choc + w//3
    w = w//3 + w%3
    
#dont forget to print the number of chocolates Sanjay can eat
print(choc)

How to Reverse Digits in Python

You will be given a number. You have to reverse the digits of the number and print it.

----------------------------------------------------------------------
Input:
A positive integer greater than zero

Output:
The number in reverse order. Check sample outputs for more details.

----------------------------------------------------------------------
Sample input:
345200

Sample output:
2543

----------------------------------------------------------------------
Sample input:
6752343

Sample output:
3432576

Solution

#take input of the number here
n = int(input())

#write code to reverse the number here
r=0

while(n>0):
    r = r*10 + n%10
    n = n//10

print(r)

How to Find Factorial of a Number in Python

Factorial is a mathematical function denoted by '!'. It is defined as

n factorial = n!= 1*2*3...*(n-1)*n

In this question, you have to make a function that will take an integer as input, and return the factorial of that integer if that integer is greater than or equal to zero and return -1 if the number is less than zero or negative.

Note: the function doesn't return print the factorial but returns it.
----------------------------------------------------------------------
Input:
An integer n

Output:
The function returns n! if n is greater than or equal to 0.
0! = 1
and the function returns -1 if the number is less than 0.

----------------------------------------------------------------------
Sample input:
3

Sample output:
6

----------------------------------------------------------------------
Sample input:
-4

Sample output:
-1

Solution

#take the input here
number=int(input())



#the function definition starts here
def factorial(n):
    #write the funtion here that finds and RETURNS factorial of next
    if n<0:
        return -1
    elif n==0:
        return 1
    else:
        f=1
        for i in range(1,n+1):
            f = f*i
        return f    
    

#function definition ends here

#do not alter the code typed below
k=factorial(number)
print(k)


Python Alarm Clock: You're trying to automate your alarm clock by writing a function for it.

You're given a day of the week encoded as 1=Mon, 2=Tue, ... 6=Sat, 7=Sun, and whether you are on vacation as a boolean value (a boolean object is either True or False. Google "booleans python" to get a better understanding). Based on the day and whether you're on vacation, write a function that returns a time in form of a string indicating when the alarm clock should ring.

When not on a vacation, on weekdays, the alarm should ring at "7:00" and on the weekends (Saturday and Sunday) it should ring at "10:00".

While on a vacation, it should ring at "10:00" on weekdays. On vacation, it should not ring on weekends, that is, it should return "off".

----------------------------------------------------------------------
Input:
The input will be a list of two elements. The first element will be an integer from 1 to 7, and the second element will be a boolean value.

Output:
The output will be a string denoting the time alarm will ring or 'off'

----------------------------------------------------------------------
Sample input:
[7, True]

Sample output:
off

----------------------------------------------------------------------
Sample input:
[3, True]

Sample output:
10:00

----------------------------------------------------------------------

Solution

#Take input here
#we will take input using ast sys
import ast
input_str = input()

#ast.literal_eval() will evaluate the string and make a data structure for the same
#here the input is a list since input is in '[...]', so ast.literal_eval() will
#make a list with the same data as passed
input_list = ast.literal_eval(input_str)

#the data or the two values in list is now changed to separate variables
day_of_the_week = input_list[0] #first element is an integer denoting the day of the week
is_on_vacation = input_list[1] #this is a boolean denoting if its vacation or not

# write your code here

#we will solve this using a function that returns a string
#later we will just print the string

def alarm_time(day_of_the_week, is_on_vacation):
    weekend = [6,7] #encoding of weekend days sat and sun are 6 and 7
    if is_on_vacation:
        if day_of_the_week not in weekend:
            return '10:00'
        else: #its weekend
            return 'off'
    else:
        if day_of_the_week not in weekend:
            return '7:00'
        else: #its weekend
            return '10:00'
#end of function

#print the result
print(alarm_time(day_of_the_week, is_on_vacation))

Python: Beautiful Pretty Sexy

A number k is beautiful if it is of the form 3n+1, is pretty if it is of the form 3n+2 and is sexy if it is of form 3n.
Given a number k, print if it is beautiful, pretty or sexy.

Sample input:
21

Sample output:
sexy

Sample input:
22

Sample output:
beautiful

Sample input:
23

Sample output:
pretty

Solution

#input has been taken for you

k=int(input())

#check if the number is beautiful, pretty or sexy

if k%3==0: #if k is of form 3n
    print('sexy')
elif k%3==1: #else if k is of form 3n+1
    print('beautiful')
elif k%3==2: #else if k is of form 3n+2
    print('pretty')

How to check number is even or odd in Python?

Code

Input:
An integer

Output:
'Even' or 'Odd'

----------------------------------------------------------------------
Sample input:
3

Sample output:
Odd

----------------------------------------------------------------------
Sample input:
6

Sample output:
Even

Solution

#Take input on your own
num= int(input())

#start writing your code from here
if num%2==0:
    print('Even')
else:
    print('Odd')

You are given two integer variables, x and y. You have to swap the values stored in x and y.

Input:
Two numbers x and y separated by a comma.

Output:
Print 5 lines. The first two lines will have values of variables shown before swapping, and the last two lines will have values of variables shown after swapping. The third line will be blank.

----------------------------------------------------------------------
Sample input:
20, 50

Sample output:

x before swapping: 20
y before swapping: 50

x after swapping: 50
y after swapping: 20

Solution

#Take input using input()

#input() takes input in form of the string
in_string=input()

#here extract the two numbers from the string

#we know the values of our interest are separated by comma so we can use split
mylist = in_string.split(',')
#['12','15']
#and now get our values 
#but they are in string so we first make them int
x = int(mylist[0])
y = int(mylist[1])

# SAJAN'S APPROACH

# #print x and y before swapping
# print('x before swapping: {0}'.format(x))
# print('y before swapping: {0}'.format(y))

# #Writing your swapping code here
# z = x
# x = y
# y = z
# print()
# #print x and y after swapping
# print('x after swapping: {0}'.format(x))
# print('y after swapping: {0}'.format(y))


#without making a new Variable
# print x and y before swapping
print('x before swapping: {0}'.format(x))
print('y before swapping: {0}'.format(y))
#Writing your swapping code here
x=x+y
y=x-y
x=x-y
print()
print('x after swapping: {0}'.format(x))
print('y after swapping: {0}'.format(y))

How to Check Palindrome String in Java?

Method - 1: Native

import java.io.*;

class Palindrom 
{
    public static boolean checkPalindrome(String str)
    {
        // To store the reverse of string
        String revStr = "";

		boolean isPalindrom = false;

		for (int i = str.length() - 1; i >= 0; i--) 
		{
			revStr = revStr + str.charAt(i);
		}

		// Checking if string and reverse of string are equal
		if (str.equals(revStr)) 
		{
			isPalindrom = true;
		}
		// return true if string are plaindrom otherwise false
		return isPalindrom;
	}
	
	public static void main(String[] args)
	{
		String str1 = "sir";
		String str2 = "madam";

		System.out.println(str1 + " is palindrom: " +checkPalindrome(str1));
		System.out.println(str2 + " is palindrom: " +checkPalindrome(str2));
	}
}

Output

sir is palindrom: false
madam is palindrom: true

Time Complexity: O(n)

Space Complexity: O(n)

Method - 2: Recursive

import java.io.*;

class GFG 
{
	public static boolean checkPalindrome(int i, int j, String A)
	{
		// comparing the two pointers
		if (i >= j) {
			return true;
		}

		// comparing the characters on those pointers
		if (A.charAt(i) != A.charAt(j)) {
			return false;
		}

		// checking everything again recursively
		return checkPalindrome(i + 1, j - 1, A);
	}

	public static boolean checkPalindrome(String A)
	{
		return checkPalindrome(0, A.length() - 1, A);
	}

	// main function
	public static void main(String[] args)
	{
	    String str1 = "sir";
        String str2 = "madam";
        
		System.out.println(str1 + " is palindrom: " +checkPalindrome(str1.toLowerCase()));
		System.out.println(str2 + " is palindrom: " +checkPalindrome(str2.toLowerCase()));
	}
}

Output

sir is palindrom: false
madam is palindrom: true

Time Complexity: O(n)

Space Complexity: O(n)

Method - 3: Two - Pointer

public class Palindrom 
{
	static boolean checkPalindrome(String str)
	{
		int i = 0, j = str.length() - 1;

		while (i < j) {

			// If there mismatch
			if (str.charAt(i) != str.charAt(j))
				return false;
				
			i++;
			j--;
		}
		
		return true;
	}

	public static void main(String[] args)
	{
		String str1 = "sir";
        String str2 = "madam";
		
		System.out.println(str1 + " is palindrom: " +checkPalindrome(str1.toLowerCase()));
		System.out.println(str2 + " is palindrom: " +checkPalindrome(str2.toLowerCase()));
	}
}

Output

sir is palindrom: false
madam is palindrom: true

Time Complexity: O(n)

Space Complexity: O(1)

How to Find Sum of Digits in Java

Method - 1

import java.io.*;

class SumDigits
{
	static int getSum(int num)
	{ 
		int sum = 0;

		while (num != 0)
		{
			sum = sum + num % 10;
			num = num / 10;
		}
	return sum;
	}

	public static void main(String[] args)
	{
		int num = 12345;
		System.out.println(getSum(num));
	}
}

Output: 15

Time Complexity: O(|n|)
Auxiliary Space: O(1)

Method - 2: Single Line

import java.io.*;

class SumDigits {
	
	static int getSum(int num)
	{
		int sum;
		for (sum = 0; num > 0; sum += num % 10, num /= 10);
		return sum;
	}

	public static void main(String[] args)
	{
		int num = 12345;
		System.out.println(getSum(num));
	}
}

Output: 15

Time Complexity: O(|n|)
Auxiliary Space: O(1)

Method - 3: Recursive

import java.io.*;

class SumDigits 
{
	static int sumDigits(int num)
	{
		return num == 0 ? 0 : num % 10 + sumDigits(num / 10);
	}

	public static void main(String[] args)
	{
	     int num = 12345;
	     System.out.println(sumDigits(num));
	}
}

Output: 15

Time Complexity: O(log10n)
Auxiliary Space: O(log10n)

Java Program to Print Numbers Divisible by 3 and 5

Code

class DivisibleThreeFive
{
    // Result function with N
	static void result(int N)
	{	 
		// iterate from 0 to N
		for (int num = 0; num < N; num++)
		{	 
			if (num % 3 == 0 && num % 5 == 0)
				System.out.print(num + " ");
		}
	}
	
	public static void main(String []args)
	{
		int N = 100;
		result(N);
	}
}

Output

0 15 30 45 60 75 90 

Time Complexity: O(N)
Auxiliary Space: O(1)

Method - 2

This can also be done by checking if the number is divisible by 15, since the LCM of 3 and 5 is 15 and any number divisible by 15 is divisible by 3 and 5 and vice versa also. 

class DivisibleThreeFive 
{
  public static void main(String[] args) 
  {
    int n = 100;
 
    for (int i = 0; i < n; i += 15) 
    {
      System.out.print(i + " ");
    }
  }
}
  • Time Complexity: O(n/15) ~= O(n) 
  • Auxiliary Space: O(1)
teststep banner