diff --git a/Programming Ques by YASHVI UPADHYAY/Q1_price_into_dollars.md b/Programming Ques by YASHVI UPADHYAY/Q1_price_into_dollars.md new file mode 100644 index 0000000..f9b4b91 --- /dev/null +++ b/Programming Ques by YASHVI UPADHYAY/Q1_price_into_dollars.md @@ -0,0 +1,211 @@ +--- +title: Price into Dollars +tags: ['formatted-string', 'index', 'data-type'] +--- + +# Problem Statement + +Given a list of prices of items in rupees and an index, **modify that index element in place into price in dollars and cents** (don't modify other indices).\ +**1 dollar = 85 rupees\ +1 dollar = 100 cents** + +- If the `index` is out of range, return **None**. +- Assume the `price_list` is list of valid **integers**. +- String output has no decimal points (as the remaining rupees is written as cents) +- **Refrain from using for/while loops** + +**Example:** +```python +PriceList = [4000, 7000] +get_price_in_dollars(PriceList, 1) # list modified [4000, '82 dollars 35 cents'] +get_price_in_dollars([142, 841, 7621, 2221],1) #list modified [142, '9 dollars 89 cents', 7621, 2221] +``` +First case: 7000 rupeess -> 82 dollars 35 cents\ +Second case: at index=1 is `841` i.e. `9 dollars 89 cents` (85 rupees -> 1 dollar & 1 dollar -> 100 cents) + + +# Solution + +```python test.py -r 'python test.py' + + +{% include '../is_equal_loops_modify_check_suffix.py.jinja' %} + +``` + +# Public Test Cases + +## Input 1 + +``` +PriceList = [1201, 2500, 7502, 4080] +if not check_for_loops(get_price_in_dollars): + modify_check( + lambda x: get_price_in_dollars(x, 0), PriceList, ['14 dollars 12 cents', 2500, 7502, 4080], should_modify=True + ) +``` + +## Output 1 + +``` +['14 dollars 12 cents', 2500, 7502, 4080] +``` + +## Input 2 + +``` +PriceList = [1500, 5000, 999] +if not check_for_loops(get_price_in_dollars): + modify_check( + lambda x: get_price_in_dollars(x, 0), PriceList, ['17 dollars 64 cents', 5000, 999], should_modify=True + ) +``` + +## Output 2 + +``` +['17 dollars 64 cents', 5000, 999] +``` + +## Input 3 + +``` +PriceList = [450, 1050, 2300] +if not check_for_loops(get_price_in_dollars): + modify_check( + lambda x: get_price_in_dollars(x, 1), PriceList, [450, '12 dollars 35 cents', 2300], should_modify=True + ) +``` + +## Output 3 + +``` +[450, '12 dollars 35 cents', 2300] +``` + +## Input 4 + +``` +PriceList = [1500, 5000, 999] +if not check_for_loops(get_price_in_dollars): + modify_check( + lambda x: get_price_in_dollars(x, 2), PriceList, [1500, 5000, '11 dollars 75 cents'], should_modify=True + ) +``` + +## Output 4 + +``` +[1500, 5000, '11 dollars 75 cents'] +``` + +## Input 5 + +``` +PriceList = [450, 1050, 2300] +if not check_for_loops(get_price_in_dollars): + modify_check( + lambda x: get_price_in_dollars(x, -1), PriceList, None, should_modify=False + ) +``` + +## Output 5 + +``` +None +``` + + +# Private Test Cases + +## Input 1 (out of range index) + +``` +PriceList = [450, 1050, 2300] +if not check_for_loops(get_price_in_dollars): #if for loop found prints "Found a 'for' loop in the function {func.__name__}.") + modify_check( + lambda x: get_price_in_dollars(x, 3), PriceList, None, should_modify=False + ) +``` + +## Output 1 + +``` +None +``` + +## Input 2 (empty list) + +``` +if not check_for_loops(get_price_in_dollars): + modify_check( + lambda x: get_price_in_dollars(x, 0), + [], + None, + should_modify=False + ) +``` + +## Output 2 + +``` +None +``` + +## Input 3 (1 item list) + +``` +PriceList = [905] +if not check_for_loops(get_price_in_dollars): + modify_check( + lambda x: get_price_in_dollars(x, 0), PriceList, ['10 dollars 64 cents'], should_modify=True + ) +``` + +## Output 3 + +``` +['10 dollars 64 cents'] +``` + +## Input 4 (1 item list) + +``` +PriceList = [2501] +if not check_for_loops(get_price_in_dollars): + modify_check( + lambda x: get_price_in_dollars(x, 0), PriceList, ['29 dollars 42 cents'], should_modify=True + ) +``` + +## Output 4 + +``` +['29 dollars 42 cents'] +``` + +## Input 5 (out of range index) + +``` +PriceList = [1200, 3400] +if not check_for_loops(get_price_in_dollars): + modify_check( + lambda x: get_price_in_dollars(x, 5), PriceList, None, should_modify=False + ) +``` + +## Output 5 + +``` +None +``` + diff --git a/Programming Ques by YASHVI UPADHYAY/Q2_find_repeated_elements.md b/Programming Ques by YASHVI UPADHYAY/Q2_find_repeated_elements.md new file mode 100644 index 0000000..949e6bc --- /dev/null +++ b/Programming Ques by YASHVI UPADHYAY/Q2_find_repeated_elements.md @@ -0,0 +1,115 @@ +--- +title: Find Repeated Elements +tags: ['set', 'filtering','lambda','data-processing'] +--- + +# Problem Statement + +Given a list of any type, return a set containing elements **which are repeated**. (case, type sensistive ==) + +**Example:** +```python +input list -> [1, 2, 3, '2', 3, 3, 4,'A','b','B','A'] #here 3,'A' have repetitions +output list -> {3, 'A'} +``` +**Refrain from for/while loops. Use functional programming like lambda/mapping etc...** + +# Solution + +```python test.py -r 'python test.py' + + +{% include '../is_equal_loops_modify_check_suffix.py.jinja' %} + +``` + +# Public Test Cases + +## Input 1 + +``` +if not check_for_loops(find_repeated_elements): + is_equal( + (find_repeated_elements([1, 2, 3, 2, 4, 5, 3, 6, 1])), + ({1, 2, 3}) + ) +``` + +## Output 1 + +``` +{1, 2, 3} +``` + +## Input 2 + +``` +if not check_for_loops(find_repeated_elements): + is_equal( + find_repeated_elements(['apple', 'banana', 'apple', 'cherry', 'banana']), + {'apple', 'banana'} + ) +``` +## Output 2 + +``` +{'apple', 'banana'} +``` + +## Input 3 + +``` +if not check_for_loops(find_repeated_elements): + is_equal( + find_repeated_elements([10, 20, 30, 40]), + set() + ) +``` + +## Output 3 + +``` +{} +``` + +# Private Test Cases + +## Input 1 + +``` +if not check_for_loops(find_repeated_elements): + is_equal( + find_repeated_elements([7, 7, 7, 7, 7]), + {7} + ) + is_equal( + find_repeated_elements([1, 2, 'apple', 2, 'banana', 'apple', 'bAnana']), + {2, 'apple'} + ) + is_equal( + find_repeated_elements([]), + set() + ) +``` + +## Output 1 + +``` +{7} +{'apple', 2} +{} +``` diff --git a/Programming Ques by YASHVI UPADHYAY/Q3_process_licenseplate.md b/Programming Ques by YASHVI UPADHYAY/Q3_process_licenseplate.md new file mode 100644 index 0000000..ae2a80a --- /dev/null +++ b/Programming Ques by YASHVI UPADHYAY/Q3_process_licenseplate.md @@ -0,0 +1,92 @@ +--- +title: Process License Plate into state, RTO code, series, unique id +tags: ['dict', 'I/O', 'list slicing','loop','multiple inputs'] +--- + +# Problem Statement + +User inputs license-plates. Process these license-plates and **print a list of dictionaries** with keys as: +1. `state`: (str) two letters which indicates the State or Union Territory in which the vehicle is registered. +2. `RTO code`: (int) a two-digit number allocated to a district RTO(s) within the respective state or Union Territory. +3. `series`: (str) 1 or 2 letter; show the ongoing registration series of respective RTO +4. `unique id` (int) between 1 and 9999; unique to each registration. + +Input preconditions: +- 1st: number of lines of input (no. of license-plates inputted) +- 2nd line onwards license-plate in the format `TN 12 L 2421`. Press enter if multiple license-plates. + +# Solution +```python test.py -r 'python test.py' + +num = int(input()) +license_plates = [] +for _ in range(num): + license_plates.append(input().strip()) + + +``` + +# Public Test Cases + +## Input 1 + +``` +5 +MH 12 L 2039 +MH 12 LQ 2930 +KA 13 ZJ 4567 +TN 08 B 7890 +DL 09 X 1023 +``` + +## Output 1 + +```python +[{'state': 'MH', 'RTO code': 12, 'series': 'L', 'unique id': 2039}, {'state': 'MH', 'RTO code': 12, 'series': 'LQ', 'unique id': 2930}, {'state': 'KA', 'RTO code': 13, 'series': 'ZJ', 'unique id': 4567}, {'state': 'TN', 'RTO code': 8, 'series': 'B', 'unique id': 7890}, {'state': 'DL', 'RTO code': 9, 'series': 'X', 'unique id': 1023}] +``` + +## Input 2 + +``` +3 +KA 10 AB 1234 +MH 05 XY 5678 +TN 03 PQ 9999 +``` + +## Output 2 + +```python +[{'state': 'KA', 'RTO code': 10, 'series': 'AB', 'unique id': 1234}, {'state': 'MH', 'RTO code': 5, 'series': 'XY', 'unique id': 5678}, {'state': 'TN', 'RTO code': 3, 'series': 'PQ', 'unique id': 9999}] +``` + + +# Private Test Cases + +## Input 1 + +``` +0 +``` + +## Output 1 + +```python +[] +``` diff --git a/Programming Ques by YASHVI UPADHYAY/Q4_Kaprekar_constant.md b/Programming Ques by YASHVI UPADHYAY/Q4_Kaprekar_constant.md new file mode 100644 index 0000000..4c02781 --- /dev/null +++ b/Programming Ques by YASHVI UPADHYAY/Q4_Kaprekar_constant.md @@ -0,0 +1,146 @@ +--- +title: Kaprekar's constant (6174) +tags: ['I/O', 'while loop', 'sort', 'join'] +--- + +# Problem Statement +Find out: how many steps are required to arrive at 6174 (Kaprekar's constant). +Follow the Method below: +1. Input any **four-digit number**. Check for *4-digits input and at-least 2-digits are unique* +2. Sort the digits to form the **largest** and **smallest** possible 4-digit numbers which can be made from the given number. +3. **Subtract** the smallest from the largest number. Note the difference number. +4. Go-back to **step 2** and repeat until the difference becomes 6174. +5. Calculate the **number of steps (int) required to reach 6174.** + +**Example:** +``` +1459 +#output: 3 +``` +largest - smallest =\ +9541 – 1459 = 8082\ +8820 – 0288 = 8532\ +8532 – 2358 = 6174\ +So, it took 3-steps to reach 6174. (If the input was 6174, then 0-steps required.) + +# Solution + +```python test.py -r 'python test.py' + +``` + +# Public Test Cases + +## Input 1 + +``` +1631 +``` + +## Output 1 + +``` +7 +``` + +## Input 2 + +``` +2468 +``` + +## Output 2 + +``` +1 +``` + +## Input 3 + +``` +3839 +``` + +## Output 3 + +``` +5 +``` + +# Private Test Cases + +## Input 1 + +``` +6174 +``` + +## Output 1 + +``` +0 +``` + +## Input 2 + +``` +24Ab +``` + +## Output 2 + +``` +None +``` + +## Input 3 + +``` +1111 +``` + +## Output 3 + +``` +None +``` + +## Input 4 + +``` +21 +``` + +## Output 4 + +``` +None +``` diff --git a/README.md b/README.md index 53c5b27..c514816 100644 --- a/README.md +++ b/README.md @@ -1 +1,9 @@ -# python-programming-questions \ No newline at end of file +# python-programming-questions +The 4 Programming Questions evaluate correctly in the local-system:\ +![image](https://github.com/user-attachments/assets/b5ee3a72-0588-4bc9-b634-f6e84d1233be) + +The type of each question is given below: +1. **Data types** - basic operations on datatypes (str -> f-string, list->indexing, int-> //, %,*) and not used loops. input are handled by a driver code, check the modified list & checked for usage of for/while loop (ignores the docstring, logic to only inspect the function's executable code). +2. **Data Processing** - basic data processing patterns like *mapping, filtering*. input handled by driver code +3. **Data Processing I/O** - inputs from the stdin and print the output to stdout in the specified format (list of dictionaries). +4. **Problem-solving** - An input output based problem-solving which involves **something different from basic data processing patterns.** (good diffcultly but doable by a beginner early weeks of Python IITM learner) diff --git a/is_equal_loops_modify_check_suffix.py.jinja b/is_equal_loops_modify_check_suffix.py.jinja new file mode 100644 index 0000000..adb9861 --- /dev/null +++ b/is_equal_loops_modify_check_suffix.py.jinja @@ -0,0 +1,118 @@ +from copy import deepcopy + +{% raw %} +def order_repr(d): + '''Print in lexicographical order of repr if dict and set''' + if isinstance(d,dict): + d = sorted(d.items(), key=lambda x:order_repr(x[0]) ) + return f"{{{', '.join(f'{order_repr(k)}: {order_repr(v)}' for k,v in d)}}}" + elif isinstance(d,set): + return f"{{{', '.join(map(order_repr,sorted(d, key=order_repr)))}}}" + else: + return repr(d) +{% endraw %} + +def order_print(d): + print(order_repr(d)) + + +import traceback +def except_wrap(func): + def inner_func(*args,**kwargs): + try: + func(*args,**kwargs) + except AssertionError as e: + print(e) + except Exception as e: + traceback.print_exception(e,limit=-1, file=sys.stdout) + return inner_func + + +def assert_equal(actual_out, expected_out, show=True): + assert expected_out is None or actual_out is not None,\ + "No output returned.\nAre you returning the output? It seems like you are not returning anything." + assert actual_out == expected_out and type(actual_out) == type(expected_out),\ + ( + 'Your output does not match expected output.\n' + f'Expected ouput (type: {type(expected_out).__name__}):\n{order_repr(expected_out)}\n' + f'Your output (type: {type(actual_out).__name__}):\n{order_repr(actual_out)}' + ) + if show: + order_print(actual_out) + +is_equal = except_wrap(assert_equal) + +@except_wrap +def modify_check(func, in_obj, expected, should_modify=True): + in_obj_old = deepcopy(in_obj) + actual_out = func(in_obj) + if should_modify: + assert in_obj_old == expected or in_obj != in_obj_old,\ + ( + f'Input {type(in_obj).__name__} is not modified. You should modify the input {type(in_obj).__name__}.\n' + f'Original ({type(in_obj).__name__}):\n{order_repr(in_obj)}\n' + f'Expected modification:\n{order_repr(expected)}' + ) + assert in_obj == expected,\ + ( + f'Incorrect modifcation of the input {type(in_obj).__name__}.\n' + f'Expected modification:\n{order_repr(expected)}\n' + f'Your modification:\n{order_repr(in_obj)}' + ) + order_print(in_obj) + else: + assert_equal(actual_out, expected,show=False) + assert in_obj_old == in_obj,\ + ( + f'Input {type(in_obj).__name__} is modified. You shouldn\'t modify the input {type(in_obj).__name__}.\n' + f'Original input ({type(in_obj).__name__}):\n{order_repr(in_obj_old)}\n' + f'Your modification:\n{order_repr(in_obj)}' + ) + order_print(actual_out) + +import inspect +import ast + +def check_for_loops(func): + """Check if the given function contains any 'for' or 'while' loops, ignoring the docstring.""" + try: + # Get the source code of the function + source_code = inspect.getsource(func) + + # Remove the docstring part if it exists + if '"""' in source_code or "'''" in source_code: + # Handling the docstring removal + start_idx = source_code.find('"""') + end_idx = source_code.find('"""', start_idx + 3) + if start_idx != -1 and end_idx != -1: + source_code = source_code[:start_idx] + source_code[end_idx + 3:] + else: + start_idx = source_code.find("'''") + end_idx = source_code.find("'''", start_idx + 3) + if start_idx != -1 and end_idx != -1: + source_code = source_code[:start_idx] + source_code[end_idx + 3:] + + # Normalize indentation to spaces (4 spaces) + source_code = source_code.replace("\t", " ") + + # Strip any leading/trailing whitespace that might affect parsing + source_code = source_code.strip() + + # Parse the cleaned source code into an AST + tree = ast.parse(source_code) + + # Check for any 'for' or 'while' loops + for node in ast.walk(tree): + if isinstance(node, (ast.For, ast.While)): + print(f"Use of a loop (for/while) in the function {func.__name__} is not allowed.") + return True + + return False + except Exception as e: + print(f"Error while checking loops: {e}") + return False + + +import sys +exec(sys.stdin.read()) +