0% found this document useful (0 votes)
51 views9 pages

INFO II Practice 3 With Solutions

The document contains Python functions and code snippets for various tasks like list processing, string manipulation, recursion, and more. Many functions have examples of calling the function and printing the output. The document appears to be sharing code for common programming tasks and data structures.

Uploaded by

Deepesh Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views9 pages

INFO II Practice 3 With Solutions

The document contains Python functions and code snippets for various tasks like list processing, string manipulation, recursion, and more. Many functions have examples of calling the function and printing the output. The document appears to be sharing code for common programming tasks and data structures.

Uploaded by

Deepesh Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1 def sum_list_elements(lst):

2 return sum(lst)
3
4 L = [1,2,3,4]
5 print(sum_list_elements(L))
10

1 def multiply_list(L):
2 s = 1
3 for i in L:
4 s *= i
5 return s
6
7
8 myList = [1,2,3,4]
9 mult1= multiply_list(myList)
10 print(mult1)
24
24

1 def count_strings_with_same_first_last_char(strings):
2 count = 0
3 for s in strings:
4 if len(s) >= 2 and s[0] == s[-1]:
5 count += 1
6 return count
7

1 def remove_duplicates(lst):
2 deduplicated_list = []
3 for item in lst:
4 if item not in deduplicated_list:
5 deduplicated_list.append(item)
6 return deduplicated_list
7
8 # Example usage:
9 original_list = [1, 2, 2, 3, 4, 4, 5]
10 result_list = remove_duplicates(original_list)
11 print(result_list)
[1, 2, 3, 4, 5]

1 def have_common_member(list1, list2):


2 return any(item in list1 for item in list2)
3
4 def common_data(list1, list2):
5 result = False
6 for x in list1:
7 for y in list2:
8 if x == y:
9 result = True
10 return result
11 return result
12
13 print(common_data([1,2,3,4,5], [5,6,7,8,9]))
14 print(common_data([1,2,3,4,5], [6,7,8,9]))

1
2 def printValues():
3 l = list()
4 for i in range(1,21):
5 l.append(i**2)
6 print(l[:5])
7 print(l[-5:])
8
9 printValues()
10
11 squared_values = [x**2 for x in range(1, 31)][5:]
12 print(squared_values)
13

1 char_list = ['a', 'b', 'c', 'd', 'e']


2 char_string = ''.join(char_list)
3 print(char_string)
abcde
1 def is_Sublist(l, s):
2 sub_set = False
3 if s == []:
4 sub_set = True
5 elif s == l:
6 sub_set = True
7 elif len(s) > len(l):
8 sub_set = False
9
10 else:
11 for i in range(len(l)):
12 if l[i] == s[0]:
13 n = 1
14 while (n < len(s)) and (l[i+n] == s[n]):
15 n += 1
16
17 if n == len(s):
18 sub_set = True
19
20 return sub_set
21
22 def is_sublist2(sublist, lst):
23 return all(item in lst for item in sublist)
24
25 a = [2,4,3,5,7]
26 b = [4,3]
27 c = [3,7]
28 print(is_Sublist(a, b))
29 print(is_Sublist(a, c))
30 print(is_sublist2(a, b))
True
False
False

1 def find_common_items(list1, list2):


2 common_items = []
3 for item1 in list1:
4 for item2 in list2:
5 if item1 == item2:
6 common_items.append(item1)
7 return common_items
8
9 # Example usage:
10 list1 = [1, 2, 3, 4, 5]
11 list2 = [3, 4, 5, 6, 7]
12 common_items = find_common_items(list1, list2)
13 print(common_items)
14
[3, 4, 5]

1 def print_nested_list(nested_list):
2 for sublist in nested_list:
3 print(sublist)
4
5 # Example usage:
6 nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print_nested_list(nested_list)
7 print_nested_list(nested_list)
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

1 def calculate_operations(a, b):


2 sum_result = a + b
3 subtraction_result = a - b
4 multiplication_result = a * b
5 return sum_result, subtraction_result, multiplication_result
6
7 num1 = 5
8 num2 = 3
9 result_sum, result_sub, result_mul = calculate_operations(num1, num2)
10 print(f"Sum: {result_sum}, Subtraction: {result_sub}, Multiplication: {result_mul}")

1 def check_presence(roll_number):
2 # Assuming some logic to determine if the student is present or absent
3 # Here, checking if the roll number is even for simplicity
4 # otherwise we can check if the number is in a list
5 return "Present" if roll_number % 2 == 0 else "Absent"
6
7 # Example usage:
8 student_roll = 101
9 attendance_status = check_presence(student_roll)
10 print(f"Student with roll number {student_roll} is {attendance_status}")
11

1 def count_vowels_and_consonants(word):
2 vowels = "aeiou"
3 vowel_count = sum(1 for char in word if char.lower() in vowels)
4 consonant_count = len(word) - vowel_count
5 return vowel_count, consonant_count
6
7 # Example usage:
8 input_word = "Hello"
9 vowels_count, consonants_count = count_vowels_and_consonants(input_word)
10 print(f"Vowels: {vowels_count}, Consonants: {consonants_count}")
11

1 def convert_to_uppercase(word):
2 return word.upper()
3
4 # Example usage:
5 lowercase_word = "python"
6 uppercase_word = convert_to_uppercase(lowercase_word)
7 print(f"Uppercase: {uppercase_word}")
8

1 def power_recursive(base, exponent):


2 if exponent == 0:
3 return 1
4 else:
5 return base * power_recursive(base, exponent - 1)
6
7 # Example usage:
8 number = 2
9 power = 3
10 result_power = power_recursive(number, power)
11 print(f"{number} raised to the power of {power} is {result_power}")
12

convert2fahren

0 -> 32.0
32 -> 89.6
100 -> 212.0

1 def convert2fahren(celsius, min_temp_fahrenheit=None):


2 """
3 Convert Celsius temperature to Fahrenheit, with an option to set a minimum temperature.
4 """
5 fahrenheit = celsius * 9/5 + 32
6 if min_temp_fahrenheit is not None and fahrenheit < min_temp_fahrenheit:
7 return min_temp_fahrenheit
8 return fahrenheit
9
10 temperatures_celsius = [0, 32, 100]
11 min_temp_fahrenheit = 459.67
12
13 for temp_celsius in temperatures_celsius:
14 result = convert2fahren(temp_celsius)
15 print(f"{temp_celsius} -> {result:.1f}")
16
17 # Test with minimum temperature
18 result_with_min_temp = convert2fahren(-20, min_temp_fahrenheit)
19 print(f"-20 -> {result_with_min_temp:.1f} (with minimum temperature {min_temp_fahrenheit:.1f
20

frame_string string

frame_string
Spanish Inquisition
Ni

*************************
** Spanish Inquisition **
*************************

********
** Ni **
********

frame_string
None
None
return

1 def frame_string(input_string):
2 """Prints the input string with a frame around it."""
3 length = len(input_string)
4 border = '*' * (length + 4)
5 content = f'** {input_string} **'
6
7 print(border)
8 print(content)
9 print(border)
10
11 frame_string("Spanish Inquisition")
12 print() # blank line
13 frame_string("Ni")
14
15 result1 = frame_string("Spanish Inquisition")
16 result2 = frame_string("Ni")
17
18 print(result1)
19 print(result2)
20
1 def insurance_tariff(age, license_years, accidents, loyalty_years):
2 if age < 25:
3 if license_years < 2:
4 if accidents == 0:
5 return "Red"
6 else:
7 return "Refused"
8 else:
9 if accidents == 0:
10 return "Orange"
11 elif accidents == 1:
12 return "Red"
13 else:
14 return "Refused"
15 else:
16 if license_years < 2:
17 if accidents == 0:
18 return "Orange"
19 elif accidents == 1:
20 return "Red"
21 else:
22 return "Refused"
23 else:
24 if accidents == 0:
25 if loyalty_years >= 1:
26 return "Green"
27 else:
28 return "Blue"
29 elif accidents == 1:
30 return "Orange"
31 elif accidents == 2:
31 elif accidents == 2:
32 return "Red"
33 else:
34 return "Refused"
35
36 age = int(input("Enter driver's age: "))
37 license_years = int(input("Enter years of holding the license: "))
38 accidents = int(input("Enter the number of accidents caused: "))
39 loyalty_years = int(input("Enter loyalty years with the company: "))
40
41 result = insurance_tariff(age, license_years, accidents, loyalty_years)
42 print(f"The insurance tariff for the driver is: {result}")
43

1 import random
2
3 # 2. function that does a turn of the game
4
5 def game_turn(current_position, dice1, dice2):
6 total_dice = dice1 + dice2
7 new_position = current_position + total_dice
8
9 # Check for special squares
10 if new_position == 52: # Jail
11 return 0
12 elif new_position == 63: # Arrival
13 return new_position
14 elif new_position > 63: # Retreat if passing square 63
15 new_position = 126 - new_position
16
17 # Check for goose squares
18 goose_squares = [9, 18, 27, 36, 45, 54]
19 if new_position in goose_squares:
20 new_position += total_dice
21
22 # Check for specific dice rolls
22 # Check for specific dice rolls
23 if (dice1, dice2) in [(3, 6), (6, 3)]:
24 new_position = 26
25 elif (dice1, dice2) in [(4, 5), (5, 4)]:
26 new_position = 53
27
28 return new_position
29
30 # 3. test the function with user-defined game state
31 current_position = 0
32
33 # You can either input dice values manually or generate random values
34 dice1 = int(input("Enter the value of the first die: "))
35 dice2 = int(input("Enter the value of the second die: "))
36 # Uncomment the following lines to generate random dice values
37 # dice1 = random.randint(1, 6)
38 # dice2 = random.randint(1, 6)
39
40 new_position = game_turn(current_position, dice1, dice2)
41
42 print(f"Current position: {current_position}, Dice values: {dice1}, {dice2}, New position:
43

You might also like